完成「有效的括号」

master
kuiki 2018-09-28 16:22:44 +08:00
commit 03b3818f6a
2 changed files with 72 additions and 0 deletions

52
valid-parentheses.go Normal file
View File

@ -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()
}

20
valid-parentheses_test.go Normal file
View File

@ -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)
}
}
}