Skip to content

Commit 39f162c

Browse files
author
hero
committed
最长公共前缀
1 parent d34e0a1 commit 39f162c

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed
Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,50 @@
11
package leet_code
22

33
import (
4+
"fmt"
45
"testing"
56
)
67

78
//最长公共前缀
89
func TestLongestCommonPrefix(t *testing.T) {
9-
t.Log(longestCommonPrefix([]string{"aa", "aa", "aa"}))
10+
t.Log(longestCommonPrefix([]string{"aca", "cba"}))
1011
}
1112

1213
func longestCommonPrefix(strs []string) string {
13-
/*if len(strs) <= 0 {
14+
if len(strs) <= 0 {
1415
return ""
1516
}
17+
if len(strs) == 1 {
18+
return strs[0]
19+
}
1620
var (
17-
result string
18-
endFor bool
21+
startData = strs[0]
22+
result string
1923
)
20-
for _, v := range strs {
21-
22-
}
23-
for index, v := range strs[0] {
24-
result += string(v)
24+
strs = strs[1:]
25+
var enFor bool
26+
for i, v := range startData {
27+
var add bool
28+
for _, v1 := range strs {
29+
if i+1 > len(v1) {
30+
enFor = true
31+
break
32+
}
33+
fmt.Println(v1[i : i+1])
34+
if string(v) == v1[i:i+1] {
35+
add = true
36+
} else {
37+
add = false
38+
enFor = true
39+
break
2540
}
2641
}
27-
if endFor {
28-
result = result[:len(result)-1]
42+
if enFor {
2943
break
3044
}
31-
}*/
32-
return "result"
45+
if add {
46+
result += string(v)
47+
}
48+
}
49+
return result
3350
}

0 commit comments

Comments
 (0)