0020.有效的括号

方法一:栈模拟

时间复杂度 $O(n)$,空间复杂度 $O(n)$,$n$ 表示字符串的长度。

func isValid(s string) bool {
	stack, parent := []byte{}, map[byte]byte{')': '(', '}': '{', ']': '['}
	for i := 0; i < len(s); i++ {
		if s[i] == '(' || s[i] == '[' || s[i] == '{' {
			stack = append(stack, s[i])
		} else {
			if len(stack) > 0 && parent[s[i]] == stack[len(stack)-1] {
				stack = stack[:len(stack)-1]
			} else {
				return false
			}
		}
	}
	return len(stack) == 0
}