编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z

longestCommonPrefix.PNG

代码写的干干巴巴,麻麻赖赖,一点都不圆润,竟然战胜了83.57% 的提交

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        int len = 0;
        int min = 999999;
        String mins = "";
        String maxs = "";
        int max = 0;
        for (String s : strs
        ) {
            if (s == null || s.equals("")) return "";
            if (s.length() < min) {
                min = s.length();
                mins = s;
            }
            if (s.length() > max) {
                max = s.length();
                maxs = s;
            }
        }
        Character v = maxs.charAt(len);
        String t = v.toString();
        boolean f = false;
        int j = 0;
        while (j < min) {
            for (int i = 0; i < strs.length; i++) {
                if (!strs[i].startsWith(t)) {
                    f = true;
                    break;
                }
            }
            if (f) {
                break;
            } else {
                len++;
                if (len >= min) {
                    return mins;
                }
                v = maxs.charAt(len);
                t += v.toString();
            }
            j++;
        }
        return strs[0].substring(0, len);
    }
}

标签: leetcode, java

添加新评论