NOTE
最长公共前缀
最长公共前缀:暴力与前缀树思路。
这是历史学习笔记,可能存在过时或不完整的理解。
1. 题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
2. 思路
- 暴力
- 前缀树?tree.md
3. 实现
暴力
func longestCommonPrefix(strs []string) string {
count := 0
longestCommonPrefixDFS(strs, 0, &count)
if count == 0{return ""}
return strs[0][:count]
}
func longestCommonPrefixDFS(strs []string, index int, count *int) {
m := make(map[byte]int, 0)
for _, str := range strs {
if index >= len(str) {return}
m[str[index]]++
}
if len(m) == 1{
(*count)++
longestCommonPrefixDFS(strs, index+1, count)
}
}
讨论
使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看