From 03b3818f6a42813451ab5221ccc780bf1b102fd1 Mon Sep 17 00:00:00 2001 From: kuiki Date: Fri, 28 Sep 2018 16:22:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E3=80=8C=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E6=8B=AC=E5=8F=B7=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- valid-parentheses.go | 52 +++++++++++++++++++++++++++++++++++++++ valid-parentheses_test.go | 20 +++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 valid-parentheses.go create mode 100644 valid-parentheses_test.go diff --git a/valid-parentheses.go b/valid-parentheses.go new file mode 100644 index 0000000..42d5a64 --- /dev/null +++ b/valid-parentheses.go @@ -0,0 +1,52 @@ +package leetcode + +type stack struct { + array [10000]string + index int +} + +var m = map[string]string{ + "}": "{", + ")": "(", + "]": "[", +} + +func (s *stack) push(r string) bool { + switch r { + case "(": + fallthrough + case "{": + fallthrough + case "[": + s.array[s.index] = r + s.index++ + case ")": + fallthrough + case "}": + fallthrough + case "]": + if s.index == 0 { + return false + } + s.index = s.index - 1 + o := m[r] + if o != s.array[s.index] { + return false + } + } + return true +} + +func (s *stack) empty() bool { + return s.index == 0 +} + +func isValid(s string) bool { + st := &stack{} + for i := 0; i < len(s); i++ { + if !st.push(s[i : i+1]) { + return false + } + } + return st.empty() +} diff --git a/valid-parentheses_test.go b/valid-parentheses_test.go new file mode 100644 index 0000000..a095bce --- /dev/null +++ b/valid-parentheses_test.go @@ -0,0 +1,20 @@ +package leetcode + +import ( + "testing" +) + +func TestIsValid(t *testing.T) { + qsts := map[string]bool{ + "()": true, + "()[]{}": true, + "(]": false, + "([)]": false, + "{[]}": true, + } + for qst, res := range qsts { + if r := isValid(qst); r != res { + t.Fatalf("quest is: %+v, except result is: %v, but exec result is: %v", qst, res, r) + } + } +}