File tree Expand file tree Collapse file tree 1 file changed +9
-16
lines changed
leetcode/0014.Longest-Common-Prefix Expand file tree Collapse file tree 1 file changed +9
-16
lines changed Original file line number Diff line number Diff line change 1
1
package leetcode
2
2
3
- import "sort"
4
-
5
3
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
18
11
}
19
12
}
20
- commonPrefix = append (commonPrefix , strs [0 ][i ])
21
13
}
22
- return string (commonPrefix )
14
+
15
+ return prefix
23
16
}
You can’t perform that action at this time.
0 commit comments