首页 > 代码库 > LeetCode Longest Common Prefix

LeetCode Longest Common Prefix

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

要减少比较次数。在实现过程中我的想法是,2个2个比较,那么只要遍历一次数组就好。而且,在比较过程中,以较短的那个长度作为最大比较距离,较长的后半部分是不可能存在公共前缀的。


public class Solution {
     public String longestCommonPrefix(String[] strs) {
       
        if(strs.length == 0)return "";
        String prefix = strs[0];
        for(int i = 1;i<strs.length;i++)
        {
            int len = strs[i].length()>prefix.length()?prefix.length():strs[i].length();
            prefix = prefix.substring(0,len);
            if(prefix.length() == 0)
                return "";
            for(int j = 0;j<len;j++)
            {
                if(prefix.charAt(j)!=strs[i].charAt(j))
                {
                    prefix = prefix.substring(0, j);
                    break;
                }
            }
        }
        return prefix;
    }
}