From acf3bb1677cdc7d1f28de7a7ac73190688d0735f Mon Sep 17 00:00:00 2001 From: kuiki Date: Fri, 28 Sep 2018 16:44:34 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E3=80=8C=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E5=89=8D=E7=BC=80=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- longest-common-prefix.go | 31 +++++++++++++++++++++++++++++++ longest-common-prefix_test.go | 33 +++++++++++++++++++++++++++++++++ question.go | 6 ++++++ 3 files changed, 70 insertions(+) create mode 100644 longest-common-prefix.go create mode 100644 longest-common-prefix_test.go create mode 100644 question.go 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{} +}