Algorithm/Daily Coding Tests Challenge
[Leetcode] Easy : Valid Parentheses
Jesip14
2021. 8. 31. 22:20
Description
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.
My solution
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for i in s:
if i in ('(', '[', '{'):
stack.append(i)
elif len(stack) == 0 and i in (')', ']', '}'):
stack.append(i)
break
elif i == ')' and stack[-1] == '(':
stack.pop()
elif i == ']' and stack[-1] == '[':
stack.pop()
elif i == '}' and stack[-1] == '{':
stack.pop()
else:
break
return True if len(stack) == 0 else False