func isValid(s string) bool {
source := []rune(s)
var stack []rune
for _, item := range source {
//栈顶元素与当前元素比较,相同则出栈,栈最后为空就行
//注意,应该是栈顶元素下标>=0,不是>0
//if lastIndex := len(stack) - 1; lastIndex > 0 && isMatch(stack[lastIndex], item) {
if lastIndex := len(stack) - 1; lastIndex >= 0 && isMatch(stack[lastIndex], item) {
//出栈
stack = stack[:lastIndex]
continue
}
stack = append(stack, item)
}
if len(stack) > 0 {
return false
}
return true
}
func isMatch(c1, c2 rune) bool {
if c1 == '(' && c2 == ')' {
return true
} else if c1 == '[' && c2 == ']' {
return true
} else if c1 == '{' && c2 == '}' {
return true
}
return false
}