We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a3c7d42 commit b5dce1aCopy full SHA for b5dce1a
leetcode/0014.Longest-Common-Prefix/14.Longest Common Prefix.go
@@ -1,23 +1,16 @@
1
package leetcode
2
3
-import "sort"
4
-
5
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)
+ prefix := strs[0]
+
+ for i := 1; i < len(strs); i++ {
+ for j := 0; j < len(prefix); j++ {
+ if len(strs[i]) <= j || strs[i][j] != prefix[j] {
+ prefix = prefix[0:j]
+ break
18
}
19
20
- commonPrefix = append(commonPrefix, strs[0][i])
21
22
+ return prefix
23
0 commit comments