day05:最长公共前缀(Java)

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

参考了以下资料:

1. https://leetcode.com/problems/longest-common-prefix/discuss/6910/Java-code-with-13-lines

2. https://cloud.tencent.com/developer/article/1327470

你可能感兴趣的:(day05:最长公共前缀(Java))