Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
func isValid(_ s: String) -> Bool { var stack = [Character](), b = true func compare(_ c: Character) -> Bool { guard let t = stack.popLast() else { return false } return (c == ")" && t == "(") || (c == "]" && t == "[" ) || (c == "}" && t == "{") } loop: for c in s { switch c { case "(", "[", "{": stack.append(c) default: b = compare(c) if !b { break loop } } } return b && stack.isEmpty } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼