代码

/**
 * @Author hang.wang
 * @Date 2023/11/24 13:38
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀,返回空字符串 ""。
 * 示例 1:
 * 输入:strs = ["flower","flow","flight"]
 * 输出:"fl"
 *
 * 示例 2:
 * 输入:strs = ["dog","racecar","car"]
 * 输出:""
 * 解释:输入不存在公共前缀。
 *
 * 提示:
 * 1 <= strs.length <= 200
 * 0 <= strs[i].length <= 200
 * strs[i] 仅由小写英文字母组成
 */
public class Class14 {

    public static void main(String[] args) {
        Class14 class14 = new Class14();
        System.out.println(class14.longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(class14.longestCommonPrefix(new String[]{"dog", "racecar", "car"}));
    }

    public String longestCommonPrefix(String[] strs) {
        List<String> collect = Arrays.stream(strs).sorted(Comparator.comparing(String::length)).collect(Collectors.toList());

        String smallest = collect.get(0);
        int index = smallest.length();
        for (int i = 0; i < smallest.length(); i++) {
            String substring = smallest.substring(0, index);
            AtomicBoolean flag = new AtomicBoolean(true);
            collect.forEach(str -> {
                if (str.indexOf(substring) != 0) {
                    flag.set(false);
                }
            });
            if (flag.get()) {
                return substring;
            }
            if (index == 1) {
                return "";
            }
            index--;
        }
        return "";
    }
}

思路

取List中最短长度的值,以此判断满不满足,节约资源,当不满足后,长度-1,把末尾的字符去掉,一直到变成空字符串

最后修改:2023 年 12 月 08 日
如果觉得我的文章对你有用,请随意赞赏