遇到左括号入栈,遇到右括号出栈并进行对比 遍历结束之后如果栈不为空也为错误
const arraySize = 1000
type Stack struct {
top int
data [arraySize]byte
}
func (this *Stack) Push(i byte) bool {
if this.top >= arraySize {
return false
}
this.data[this.top] = i
this.top ++
return true
}
func (this *Stack) Pop() (byte, bool) {
if this.top == 0 {
return '0', false
}
this.top --
n := this.data[this.top]
return n, true
}
func isValid(s string) bool {
st := &Stack{}
m := map[byte]byte{'(': ')', '[': ']', '{': '}'}
for _, b := range s {
if _, ok := m[byte(b)]; ok {
st.Push(byte(b))
} else {
key, ok := st.Pop()
if !ok {
return false
}
if byte(b) != m[byte(key)] {
return false
}
}
}
if _, ok := st.Pop(); ok {
return false
}
return true
}