Leetcode14 Longest Common Prefix

Posted chason95

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode14 Longest Common Prefix相关的知识,希望对你有一定的参考价值。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        if(strs.length==1) return strs[0];
        int min_len = strs[0].length();
        for(int i=1;i<strs.length;i++){
            min_len = Math.min(min_len,strs[i].length());
        }
        int index=0;
        for(;index<min_len;index++){
            boolean isPrefix = true;
            for(int i=0;i<strs.length-1;i++){
                if(strs[i].charAt(index)!=strs[i+1].charAt(index)){
                    isPrefix=false;break;
                }
            }
            if (!isPrefix) {break;}
        }
        if(index==0) return "";
        else return strs[0].substring(0,index);
    }
}

8ms,47.18%.

结合最快方法改进:

    public String longestCommonPrefix(String[] strs) {
        if(strs==null||strs.length==0) return "";
        int min_len = strs[0].length();
        for(int i=1;i<strs.length;i++){
            min_len = Math.min(min_len,strs[i].length());
        }
        for(int i=0;i<min_len;i++){
            char c = strs[0].charAt(i);
            for(int j=1;j<strs.length;j++){
                if(c!=strs[j].charAt(i)) return strs[0].substring(0,i);
            }
        }
        return strs[0].substring(0,min_len);
    }

有时4ms,99.91%,有时8ms。。可以了。

以上是关于Leetcode14 Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 14Longest Common Prefix

Leetcode 14. Longest Common Prefix

Leetcode14. Longest Common Prefix

Leetcode 14 Longest Common Prefix

LeetCode 14: Longest Common Prefix

leetcode 14. Longest Common Prefix