class Solution:
def isValid(self, s: str) -> bool:
stack = []
result = []
left_into_right_dict = {
"(" : ")",
"{": "}",
"[": "]"
}
for char in s:
# print(stack, char)
if len(stack) > 0:
top = stack[-1]
# print(right_end.values())
if char in left_into_right_dict.values():
# print("hahah", top)
if top in left_into_right_dict.keys() and char == left_into_right_dict[top]:
stack.pop()
continue
stack.append(char)
else:
stack.append(char)
if len(stack) < 1:
return True
return False
Now, when the closing part comes, if it matches the corresponding opening part, it indicates that it is a balancing part and the parenthesis is removed from the stack.
Thus if after processing the string if the stack is empty, the parentheses are balanced.