Given a string s 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.
- Every close bracket has a corresponding open bracket of the same type.
Constraints:
1 <= s.length <= 104sconsists of parentheses: only ’()[]{}’.
The approach is clear straightforward: go through the string from left to right, making sure that all of the conditions are satisfied as we do so. The tricky part is how we make sure they are satisfied.
Notice that all of the conditions have to be satisfied as pairs.
This behaviour is last in, first out: the last open bracket considered is the first to be discarded. A stack is the perfect tool for the job.
def isValid(s: str) -> bool:
stack = []
for char in s:
if char is an open bracket:
add char to the stack
if char is a closed bracket:
if stack is empty: return False
pop the last open bracket off the stack
if the last open bracket is not the same type:
return False
return whether stack is empty or not
...
There are two caveats that should be noted.
def isValid(self, s: str) -> bool:
stack = []
reverses = {
"(": ")",
"[": "]",
"{": "}"
}
for char in s:
if char in "([{":
stack.append(reverses[char])
elif char in ")]}":
if len(stack) < 1:
return False
last = stack.pop()
if last != char:
return False
return len(stack) == 0
This algorithm has one loop of iterations, with each iteration taking constant time. Outside the loop, it only has constant time operations. Therefore, it is in time.
In the worst case, the stack has elements inside. Other variables have constant space. Therefore, the algorithm uses space.