完成「最长公共前缀」

master
kuiki 2018-09-28 16:44:34 +08:00
parent 03b3818f6a
commit acf3bb1677
3 changed files with 70 additions and 0 deletions

31
longest-common-prefix.go Normal file
View File

@ -0,0 +1,31 @@
package leetcode
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
if len(strs) == 1 {
return strs[0]
}
var index int
first := strs[0]
secList := strs[1:]
max := len(first)
for _, str := range secList {
l := len(str)
if l < max {
max = l
}
}
OUTLOOP:
for i := 0; i < max; i++ {
c := first[i : i+1]
for _, str := range secList {
if str[i:i+1] != c {
break OUTLOOP
}
}
index = i + 1
}
return first[:index]
}

View File

@ -0,0 +1,33 @@
package leetcode
import (
"testing"
)
func TestLongestCommonPrefix(t *testing.T) {
qsts := []question{
question{
Q: []string{},
A: "",
},
question{
Q: []string{"abc"},
A: "abc",
},
question{
A: "fl",
Q: []string{"flower", "flow", "flight"},
},
question{
A: "",
Q: []string{"dog", "racecar", "car"},
},
}
for _, q := range qsts {
qst := q.Q.([]string)
res := q.A.(string)
if r := longestCommonPrefix(qst); r != res {
t.Fatalf("quest is: %+v, except result is: %v, but exec result is: %v", qst, res, r)
}
}
}

6
question.go Normal file
View File

@ -0,0 +1,6 @@
package leetcode
type question struct {
Q interface{}
A interface{}
}