Skip to content

Commit b5dce1a

Browse files
committed
Added solution without importing sort
1 parent a3c7d42 commit b5dce1a

File tree

1 file changed

+9
-16
lines changed

1 file changed

+9
-16
lines changed
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
}

0 commit comments

Comments
 (0)