Skip to content

Commit df8b967

Browse files
aQuaaQua
aQua
authored and
aQua
committed
added Problem 14
1 parent 46fa0cd commit df8b967

File tree

3 files changed

+48
-8
lines changed

3 files changed

+48
-8
lines changed

Algorithms/0014.longest-common-prefix/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)
22

33
## 题目
4-
4+
Write a function to find the longest common prefix string amongst an array of strings.
55

66
## 解题思路
7-
7+
1.
88

99
## 总结
1010

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,30 @@
11
package Problem0014
22

3+
func longestCommonPrefix(strs []string) string {
4+
short := shortest(strs)
5+
6+
for i, r := range short {
7+
for j := 0; j < len(strs); j++ {
8+
if strs[j][i] != byte(r) {
9+
return strs[j][:i]
10+
}
11+
}
12+
}
13+
14+
return short
15+
}
16+
17+
func shortest(strs []string) string {
18+
if len(strs) == 0 {
19+
return ""
20+
}
21+
22+
res := strs[0]
23+
for _, s := range strs {
24+
if len(res) > len(s) {
25+
res = s
26+
}
27+
}
28+
29+
return res
30+
}

Algorithms/0014.longest-common-prefix/longest-common-prefix_test.go

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ type question struct {
1414
// para 是参数
1515
// one 代表第一个参数
1616
type para struct {
17-
one string
17+
one []string
1818
}
1919

2020
// ans 是答案
@@ -27,18 +27,30 @@ func Test_Problem0014(t *testing.T) {
2727
ast := assert.New(t)
2828

2929
qs := []question{
30-
3130
question{
32-
para{""},
31+
para{
32+
[]string{"abcdd", "abcde", "ab"},
33+
},
34+
ans{"ab"},
35+
},
36+
question{
37+
para{
38+
[]string{"abcdd", "abcde"},
39+
},
40+
ans{"abcd"},
41+
},
42+
question{
43+
para{
44+
[]string{},
45+
},
3346
ans{""},
3447
},
35-
3648
// 如需多个测试,可以复制上方元素。
3749
}
3850

3951
for _, q := range qs {
4052
a, p := q.ans, q.para
41-
42-
ast.Equal(a.one, p.one, "输入:%v", p)
53+
54+
ast.Equal(a.one, longestCommonPrefix(p.one), "输入:%v", p)
4355
}
4456
}

0 commit comments

Comments
 (0)