跳转至

14.最长公共前缀

先以数组的第一个元素为前缀,然后遍历依次获取公共的字符串。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0)
            return "";
        String prefix = strs[0];
        for (int i = 1; i < strs.length && prefix.length() > 0; i++) {
            prefix = getPrefix(prefix, strs[i]);
        }
        return prefix;
    }
    public String getPrefix(String prefix, String str) {
        int length = prefix.length() > str.length() ? str.length() : prefix.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            if (prefix.charAt(i) == str.charAt(i))
                sb.append(prefix.charAt(i));
            else
                return sb.toString();
        }
        return sb.toString();
    }
}

看到的另外一种思路:

class Solution {
    public String longestCommonPrefix(String[] strs) {
       if(strs == null || strs.length == 0)    return "";
        String pre = strs[0];
        int i = 1;
        while(i < strs.length){
            while(strs[i].indexOf(pre) != 0)
                pre = pre.substring(0,pre.length()-1);
            if(pre.length() == 0)
                break;
            i++;
        }
        return pre;
    }
}