问题描述
LeetCode 14. 最长公共前缀 (opens in a new tab),难度简单。
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]仅由小写英文字母组成
题解
Solution.java
class Solution {
    public String longestCommonPrefix(String[] strs) {
        int index = 0;
        // 如果是一个字符串,直接返回
        if (strs.length == 1) {
            return strs[0];
        }
        while (true) {
            for (int i = 0; i < strs.length - 1; ++i) {
                // 如果存在多个空串,直接返回
                if (Objects.equals(strs[i], "")) return "";
                // 判断字符串长度
                if (strs[i].length() < index + 1 || strs[i + 1].length() < index + 1 || strs[i].charAt(index) != strs[i + 1].charAt(index)) {
                    return strs[i].substring(0, index);
                }
            }
            index++;
        }
    }
}