Update 0014 solution

This commit is contained in:
halfrost
2021-12-21 21:21:21 +08:00
parent 90ee2871be
commit 296c2b6e5c

View File

@ -40,27 +40,21 @@ If there is no common prefix, return an empty string "".
package leetcode package leetcode
import "sort"
func longestCommonPrefix(strs []string) string { func longestCommonPrefix(strs []string) string {
sort.Slice(strs, func(i, j int) bool { prefix := strs[0]
return len(strs[i]) <= len(strs[j])
}) for i := 1; i < len(strs); i++ {
minLen := len(strs[0]) for j := 0; j < len(prefix); j++ {
if minLen == 0 { if len(strs[i]) <= j || strs[i][j] != prefix[j] {
return "" prefix = prefix[0:j]
} break
var commonPrefix []byte
for i := 0; i < minLen; i++ {
for j := 1; j < len(strs); j++ {
if strs[j][i] != strs[0][i] {
return string(commonPrefix)
} }
} }
commonPrefix = append(commonPrefix, strs[0][i])
} }
return string(commonPrefix)
return prefix
} }
``` ```