diff --git a/longest-common-prefix.go b/longest-common-prefix.go new file mode 100644 index 0000000..0a9256d --- /dev/null +++ b/longest-common-prefix.go @@ -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] +} diff --git a/longest-common-prefix_test.go b/longest-common-prefix_test.go new file mode 100644 index 0000000..ace138a --- /dev/null +++ b/longest-common-prefix_test.go @@ -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) + } + } +} diff --git a/question.go b/question.go new file mode 100644 index 0000000..9cf303f --- /dev/null +++ b/question.go @@ -0,0 +1,6 @@ +package leetcode + +type question struct { + Q interface{} + A interface{} +}