Added solution without importing sort

This commit is contained in:
Breno Baptista
2021-12-20 20:47:59 -03:00
parent a3c7d4247c
commit b5dce1a2f0

View File

@ -1,23 +1,16 @@
package leetcode
import "sort"
func longestCommonPrefix(strs []string) string {
sort.Slice(strs, func(i, j int) bool {
return len(strs[i]) <= len(strs[j])
})
minLen := len(strs[0])
if minLen == 0 {
return ""
}
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)
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
}
}
commonPrefix = append(commonPrefix, strs[0][i])
}
return string(commonPrefix)
return prefix
}