# O(n) time || O(n) space
def is_valid(self, s: str) -> bool:
closed_to_open = {'}': '{', ']': '[', ')': '('}
stack = []
for br in s:
if br in closed_to_open:
if not stack or stack.pop() != closed_to_open[br]:
return False
else:
stack.append(br)
return not stack
- Initialize an empty stack.
- Traverse the string character by character.
- For each character:
- If it’s an open bracket (’(’, ‘{’, or ‘[’), push it onto the stack.
- If it’s a closing bracket, check the top of the stack:
- If the stack is empty, the string is not valid.
- If the top of the stack is not the corresponding open bracket, the string is not valid.
- If the top of the stack is the corresponding open bracket, pop the stack.
- After traversing the string, if the stack is not empty, the string is not valid.
- If we pass the above checks, the string is valid.