public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) {
        return "";
    }
    int len = strs[0].length();
    for (int i = 0; i < len; i++) {
        char c = strs[0].charAt(i);
        for (int j = 1; j < strs.length; j++) {
            if (i == strs[j].length() || strs[j].charAt(i) != c) {
                return strs[0].substring(0, i);
            }
        }
    }
    return strs[0];
}

算法分析:

  • 时间复杂度:$O(S)$,其中 $S$ 是所有字符串中字符数量的总和,最坏情况下,所有 $n$ 个字符串都是相同的,算法会将每个字符都比较 $n$ 次。
  • 空间复杂度:$O(1)$,使用常量级空间
用java代码编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀返回空字符串 。

原文地址: https://www.cveoy.top/t/topic/hfc3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录