原题
https://leetcode.cn/problems/longest-common-prefix/description/
思路
遍历
复杂度
时间:O(n * m), n = len(strs), m = len(strs[0])
空间:O(m)
Python代码
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ''
for i in range(len(strs[0])):
isCommon = True
prefix = strs[0][:i+1]
# 检查其他字符串是否包含公共前缀
for j in range(1, len(strs)):
if strs[j].find(prefix) != 0:
isCommon = False
break
if isCommon:
ans = prefix
else:
break
return ans
Go代码
import "strings"
func longestCommonPrefix(strs []string) string {
var ans string
str := strs[0]
for i, _ := range str {
isCommon := true
prefix := str[:i+1]
// 检查其他字符串是否包含公共前缀
for j := 1; j < len(strs); j++ {
k := strings.Index(strs[j], prefix)
if k != 0 {
isCommon = false
break
}
}
if isCommon {
ans = prefix
} else {
break
}
}
return ans
}
最长公共前缀算法解析
326

被折叠的 条评论
为什么被折叠?



