14. Longest Common Prefix - LeetCode

Description:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

Accepted
545,939
Submissions
1,598,573


Solution:

 

 

 

 

class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        if(strs ==null||strs.length==0){
            return "";
        }
        
        String res = "";
        
        boolean flag = true;
        
        for(int i = strs[0].length(); i>=0; i--){
            flag = true;
            String tmp = strs[0].substring(0,i); 
           // System.out.println(strs[0].substring(0,i));
            
            for(int j = 1; j< strs.length;j++){
                //System.out.println(" j "+ strs[j]);
                if(strs[j].indexOf(tmp)!=0){
                    flag = false;
                    break; 
                }
            }
            //System.out.println(strs[0].substring(0,i));
           if(flag){
               return  tmp;
               
           }
            
        }
       
       
        return "";
    }
}

 

 

posted @ 2019-09-23 15:17  CodingYM  阅读(141)  评论(0编辑  收藏  举报