leetcode 最长公共前缀

118 / 118 个通过测试用例
状态:通过
执行用时:1 ms
内存消耗:37.2 MB

class Solution {
    public String longestCommonPrefix(String[] strs) {
       if (strs == null || strs.length == 0) return "";
        int len = strs[0].length(),tempi = 0;
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].length() < len){
                len = strs[i].length();
                tempi = i;
            }
        }
        String s = strs[tempi];
        int count=0;

        for (int i = 0; i < len; i++) {
            s = s.substring(0,len-i);
            for (int j = 0; j < strs.length; j++) {
                if (!strs[j].substring(0,s.length()).contains(s))break;
                if (strs[j].substring(0,s.length()).contains(s))count++;
            }
            //System.out.println(s+","+count);
            if (count == strs.length)return s;
            count=0;
        }

        return "";
       
    }
}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页