commit 03b3818f6a42813451ab5221ccc780bf1b102fd1 Author: kuiki Date: Fri Sep 28 16:22:44 2018 +0800 完成「有效的括号」 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) + } + } +}