leetcode——14. 最长公共前缀

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        s=''
        if strs==[] :
            return ''
        if '' in strs:
            return ''
        for i in range(len(strs[0])):
            for j in range(1,len(strs)):
                if i<len(strs[j]) and strs[j][i]!=strs[0][i]:
                    return s
                if i==len(strs[j]):
                    return s
            s+=strs[0][i]
        return s
执行用时 :44 ms, 在所有 python3 提交中击败了89.44%的用户
内存消耗 :13.7 MB, 在所有 python3 提交中击败了5.53%的用户
 
                                                          ——2019.10.17
 

两两依次对比之后得到结果
public String longestCommonPrefix(String[] strs) {  //最长公共前缀,要首先找出长度最小的字符串,然后进行比较;
        //或者是依次进行比较,更新最短长度,
        int n = strs.length;
        if(n == 0){
            return "";
        }
        if(n ==1){
            return strs[0];
        }
        String st = strs[0];
        if(st.equals("")){
            return "";
        }
        int maxLen = Integer.MAX_VALUE;
        for(int i = 1;i<n;i++){
            int m1 = Math.min(strs[i].length(),strs[i-1].length());
            int j = 0;
            for(;j<m1;j++){
                if(strs[i].equals(strs[i - 1])){
                    maxLen = Math.min(maxLen,m1);
                }else if(strs[i].charAt(j) != strs[i-1].charAt(j)){
                    maxLen = Math.min(maxLen,j);
                }
            }
            if(j == m1){
                maxLen = Math.min(maxLen,j);
            }
        }
        return strs[0].substring(0,maxLen);
    }

 

 

看了别人如下的答案,简直绝妙啊

public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prex = strs[0];
        for(String str : strs) {
            while(str.indexOf(prex) != 0) {
                prex = prex.substring(0, prex.length() -1);
            }
        }
        return prex;
    }

 

 

——2020.7.7

posted @ 2019-10-18 14:10  欣姐姐  阅读(179)  评论(0编辑  收藏  举报