完成「有效的括号」
commit
03b3818f6a
|
|
@ -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()
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue