leecode14. 最长公共前缀

好久没练leecode,怕自己费了,本来就是渣渣一枚。

思路:step1:找数组里面的最短字符串

           step2:遍历数组里面的所有字符串,看是否是相同的,相同就放入stringbuilder,否则可以返回了

最后通过的代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder sb=new StringBuilder();
        int len=strs.length;
        if(len==0) return sb.toString();;
        int min=strs[0].length();
        for (int i = 0; i < len; i++) {
            min = Math.min(min, strs[i].length());
        }
        if(min==0) return sb.toString();
        for (int j = 0; j <min ; j++) {
            char c=strs[0].charAt(j);
            for (int i = 0; i < len; i++) {
                 if(c!=strs[i].charAt(j))
                     return sb.toString();
            }

            sb.append(c);
        }
        return sb.toString();

    
        
    }
}

猜你喜欢

转载自blog.csdn.net/fyyf168lee/article/details/84998344