美文网首页
2018-11-30 最长公共前缀

2018-11-30 最长公共前缀

作者: 天际神游 | 来源:发表于2018-11-30 09:24 被阅读0次

    题目:

    最长公共前缀

    解法:

    比较简单, 直接拿其中一个字符串作为对比字符串, 然后从第一位开始往后对比. 如果有不相等的或者是超出字符串长度的, 便认为已经找到最长子串.

    public String longestCommonPrefix(String[] strs) {
        if(strs==null || strs.length < 1){
            return "";
        }
        if(strs.length == 1){
            return strs[0];
        }
    
        String cmpStr = strs[0];
        int count = 0;
        // 是否找到最长子串了
        boolean isFind = false;
        while(count < cmpStr.length()){
            char cmpChar = cmpStr.charAt(count);
            for(int i=1; i< strs.length; i++){
                String str = strs[i];
                if( (str.length() == count) || (str.charAt(count) != cmpChar) ){
                    isFind = true;
                    break;
                }
            }
            if(isFind){
                break;
            }
            count++;
        }
        return cmpStr.substring(0, count);
    }
    

    相关文章

      网友评论

          本文标题:2018-11-30 最长公共前缀

          本文链接:https://www.haomeiwen.com/subject/ypdccqtx.html