-
Notifications
You must be signed in to change notification settings - Fork 0
/
0014-longestCommonPrefix.go
79 lines (68 loc) · 1.32 KB
/
0014-longestCommonPrefix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
)
func longestCommonPrefix(strs []string) string {
lenStr := len(strs)
if lenStr == 0 {
return ""
}
if lenStr == 1 {
return strs[0]
}
if lenStr == 2 {
return longestPrefixOfTwo(strs[0], strs[1])
}
preLeft := longestCommonPrefix(strs[:lenStr/2])
if longestCommonPrefix(strs[:lenStr/2]) == "" {
return ""
}
preRight := longestCommonPrefix(strs[lenStr/2:])
if preRight == "" {
return ""
}
return longestPrefixOfTwo(preLeft, preRight)
}
func longestPrefixOfTwo(s1, s2 string) string {
var pre []byte
if len(s1) > len(s2) {
s1, s2 = s2, s1
}
for i := 0; i < len(s1); i++ {
if s1[i] == s2[i] {
pre = append(pre, s1[i])
} else {
break
}
}
if len(pre) == 0 {
return ""
}
return string(pre)
}
func longestCommonPrefixFast(strs []string) string {
if len(strs) == 0 {
return ""
}
s1 := strs[0]
i := 0
for ; i < len(s1); i++ {
char := s1[i]
for j := 1; j < len(strs); j++ {
if i < len(strs[j]) && strs[j][i] == char {
continue
} else {
return s1[:i]
}
}
}
return s1[:i]
}
func testLongestCommonPrefix() {
//s1 := "zhzuyanxi"
//s2 := "zhzh"
//s3 := "zhuxiwang"
strs := []string{}
//fmt.Println(longestPrefixOfTwo(s1, s2))
fmt.Println(longestCommonPrefix(strs))
}