Skip to content

Commit 296c2b6

Browse files
committed
Update 0014 solution
1 parent 90ee287 commit 296c2b6

File tree

1 file changed

+10
-16
lines changed

1 file changed

+10
-16
lines changed

website/content/ChapterFour/0001~0099/0014.Longest-Common-Prefix.md

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -40,27 +40,21 @@ 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
}
57+
6458
```
6559

6660

0 commit comments

Comments
 (0)