acautomaton
acautomaton
Published on 2025-01-17 / 0 Visits
0
0

Leetcode 14. 最长公共前缀

题干

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

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

 

示例 1:

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

示例 2:

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

 

提示:

  • 1 <= strs.length <= 200

  • 0 <= strs[i].length <= 200

  • strs[i] 如果非空,则仅由小写英文字母组成

初见

纵向比较每一位,当失配时返回即可。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder stringBuilder = new StringBuilder();
        int minLength = strs[0].length();
        for (int i = 1; i < strs.length; i++) {
            minLength = minLength < strs[i].length() ? minLength : strs[i].length(); 
        }
        for (int i = 0; i < minLength; i++) {
            char currentCharacter = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (currentCharacter != strs[j].charAt(i)) {
                    return stringBuilder.toString();
                }
            }
            stringBuilder.append(currentCharacter);
        }
        return stringBuilder.toString();
    }
}


Comment