mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-07 01:44:56 +08:00
Merge pull request #217 from brenobaptista/update-14
Update problem #14
This commit is contained in:
@ -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
|
||||
}
|
||||
|
@ -33,6 +33,11 @@ func Test_Problem14(t *testing.T) {
|
||||
para14{[]string{"dog", "racecar", "car"}},
|
||||
ans14{""},
|
||||
},
|
||||
|
||||
{
|
||||
para14{[]string{"ab", "a"}},
|
||||
ans14{"a"},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 14------------------------\n")
|
||||
|
@ -40,25 +40,18 @@ If there is no common prefix, return an empty string "".
|
||||
|
||||
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
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user