leetcode 14. 最长公共前缀

164 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

题目描述

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

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

示例 1:

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

示例 2:

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

提示

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成

题解

1.选择第一个作为比较对象(选择哪个都随意)

2.从第二个字符串开始,与比较对象逐个进行比较,当不相等时,将比较对象进行裁剪(通过count变量记录长度)

3.当count长度为0时,直接返回""

public static String longestCommonPrefix(String[] strs) {
        int count = 0;
        // 第一位作为比较对象
        String temp = strs[0];
        int length;
        // 跳过第一位开始比较
        for (int i = 1; i < strs.length; i++) {
            // 循环的长度
            length = Math.min(temp.length(), strs[i].length());
            for (int j = 0; j < length; j++) {
                // 比较相同位置的字符
                if (temp.charAt(j) == strs[i].charAt(j)) {
                    count ++;
                }else {
                    break;
                }
            }
            // 没有相同内容,直接返回
            if (count == 0) {
                return "";
            }
            // 更新相同的字符串
            temp = temp.substring(0,count);
            count = 0;
        }
        return temp;
    }

image.png

2.startWith

使用startWith方法代替for循环一个个比较

public static String longestCommonPrefixs(String[] strs) {
        // 第一位作为比较对象
        String temp = strs[0];
        // 跳过第一位开始比较
        for (int i = 1; i < strs.length; i++) {
            while (temp.length()>0) {
                // 使用startWith比较
                if (strs[i].startsWith(temp)) {
                    break;
                }
                // startWith失败,将长度减小
                else {
                    temp = temp.substring(0,temp.length() - 1);
                }
            }
            if (temp.length() == 0) {
                return "";
            }
        }
        return temp;
    }

image.png