LeetCode 14. 最长公共前缀

题目描述

14. 最长公共前缀

image-20230311180835705

思路分析

逐个字符比较所有字符串在同一位置的字符,直到发现某个位置的字符不相同。

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
func longestCommonPrefix(strs []string) string {
    p := strs[0]
    for i := 0; i < len(p); i++ {
        for j := 1; j < len(strs); j++ {
            s := strs[j]
            if i >= len(s) ||  p[i] != s[i] {
                return p[:i]
            }
        }
    }
    return p
}
  • 时间复杂度:O(n * m),其中 n 是字符串的数量,m 是最短字符串的长度。
  • 空间复杂度:O(1),只使用了常量级的额外空间。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/75574694
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!