LeetCode Problem #20
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Constraints
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
Solution
func isValid(_ s: String) -> Bool {
var stack = [Character]()
let pairs: [Character : Character] = ["(" : ")", "[" : "]", "{" : "}"]
for char in s {
switch char {
case "(", "[", "{":
stack.append(char)
default:
if !stack.isEmpty, char == pairs[stack.last!]! {
stack.removeLast()
} else {
return false
}
}
}
return stack.isEmpty
}