Weikoi

导航

Leetcode-014-最长公共前缀

本题比较简单,遍历就好,o(M*N)时间复杂度,遍历终止的条件是长度到头或者某一位字符互不相等。

class Solution {
    public String longestCommonPrefix(String[] strs) {

            if(strs.length==0)return "";

            for(int i=0;i<strs[0].length();i++){
                for(int j=1; j<strs.length;j++){
                    if(strs[j].length()==i||strs[j].charAt(i)!=strs[0].charAt(i)){
                        return strs[0].substring(0, i);
                    }
                }
            }
            return strs[0];
    }
}
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs: return ""
        for i in range(len(strs[0])):
            for j in range(len(strs)):
                if len(strs[j])==i or strs[j][i]!=strs[0][i]:
                    return strs[0][:i]
        return strs[0]

 

posted on 2020-03-05 15:11  Weikoi  阅读(91)  评论(0编辑  收藏  举报