讨论/《数组和字符串》 - 最长公共前缀/
《数组和字符串》 - 最长公共前缀
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        int minStrLength=Integer.MAX_VALUE;
        String minStr=null;
        for (String str : strs) {
            if(str.length()<minStrLength){
                minStrLength=str.length();
                minStr=str;
            }
        }
        int maxCommonLength=0;
        for (int i = 0; i < minStrLength; i++) {
            char c = minStr.charAt(i);
            for (int j = 0; j < strs.length; j++) {
                if(strs[j].charAt(i)!=c){
                    maxCommonLength=i-1;
                    return minStr.substring(0,maxCommonLength+1);
                }
            }
            maxCommonLength=i;
        }
        return minStr;
    }
}
展开全部 25 讨论