Skip to content

Commit 90ee287

Browse files
authored
Merge pull request halfrost#217 from brenobaptista/update-14
Update problem halfrost#14
2 parents 0468622 + 24a8bbf commit 90ee287

File tree

3 files changed

+24
-33
lines changed

3 files changed

+24
-33
lines changed
Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,16 @@
11
package leetcode
22

3-
import "sort"
4-
53
func longestCommonPrefix(strs []string) string {
6-
sort.Slice(strs, func(i, j int) bool {
7-
return len(strs[i]) <= len(strs[j])
8-
})
9-
minLen := len(strs[0])
10-
if minLen == 0 {
11-
return ""
12-
}
13-
var commonPrefix []byte
14-
for i := 0; i < minLen; i++ {
15-
for j := 1; j < len(strs); j++ {
16-
if strs[j][i] != strs[0][i] {
17-
return string(commonPrefix)
4+
prefix := strs[0]
5+
6+
for i := 1; i < len(strs); i++ {
7+
for j := 0; j < len(prefix); j++ {
8+
if len(strs[i]) <= j || strs[i][j] != prefix[j] {
9+
prefix = prefix[0:j]
10+
break
1811
}
1912
}
20-
commonPrefix = append(commonPrefix, strs[0][i])
2113
}
22-
return string(commonPrefix)
14+
15+
return prefix
2316
}

leetcode/0014.Longest-Common-Prefix/14.Longest Common Prefix_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ func Test_Problem14(t *testing.T) {
3333
para14{[]string{"dog", "racecar", "car"}},
3434
ans14{""},
3535
},
36+
37+
{
38+
para14{[]string{"ab", "a"}},
39+
ans14{"a"},
40+
},
3641
}
3742

3843
fmt.Printf("------------------------Leetcode Problem 14------------------------\n")

leetcode/0014.Longest-Common-Prefix/README.md

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -40,25 +40,18 @@ If there is no common prefix, return an empty string "".
4040

4141
package leetcode
4242

43-
import "sort"
44-
4543
func longestCommonPrefix(strs []string) string {
46-
sort.Slice(strs, func(i, j int) bool {
47-
return len(strs[i]) <= len(strs[j])
48-
})
49-
minLen := len(strs[0])
50-
if minLen == 0 {
51-
return ""
52-
}
53-
var commonPrefix []byte
54-
for i := 0; i < minLen; i++ {
55-
for j := 1; j < len(strs); j++ {
56-
if strs[j][i] != strs[0][i] {
57-
return string(commonPrefix)
44+
prefix := strs[0]
45+
46+
for i := 1; i < len(strs); i++ {
47+
for j := 0; j < len(prefix); j++ {
48+
if len(strs[i]) <= j || strs[i][j] != prefix[j] {
49+
prefix = prefix[0:j]
50+
break
5851
}
5952
}
60-
commonPrefix = append(commonPrefix, strs[0][i])
6153
}
62-
return string(commonPrefix)
54+
55+
return prefix
6356
}
64-
```
57+
```

0 commit comments

Comments
 (0)