美文网首页
leetcode 最长公共前缀

leetcode 最长公共前缀

作者: 韩新虎 | 来源:发表于2018-12-13 23:43 被阅读0次

    easy

    public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return "";
            }
            StringBuffer buffer = new StringBuffer();
    
    
            int i = 0;
    
            while (true) {
                char c;
                if (strs[0].length() == i) {
                    break;
                } else {
                    c = strs[0].charAt(i);
                }
                boolean same = true;
                for (String s : strs) {
                    if (s.length() == i) {
                        same = false;
                        break;
                    }
                    if (c != s.charAt(i)) {
                        same = false;
                        break;
                    }
                }
                if (!same) {
                    break;
                }
                buffer.append(c);
                i++;
            }
            return buffer.toString();
        }
    

    相关文章

      网友评论

          本文标题:leetcode 最长公共前缀

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