Intuition
when we travel the string we want to see the string are matched or not so we have to use stack to solve this problem
Approach
we can implement a stack to store the character if the character placed in left then put it in stack if not check the current character and the top of the stack if they are not matched return false if not pop the top character when the iteration finished check the stack if it is empty if it is return true else return false
Complexity
- Time complexity:
O(n)
- Space complexity:
O(n)
Code
class Solution:
def isValid(self, s: str) -> bool:
stack=[]
for c in s:
if c in '([{':
stack.append(c)
else:
if not stack or \
(c==')' and stack[-1]!='(') or \
(c=='}' and stack[-1]!='{') or \
(c==']' and stack[-1]!='['):
return False
stack.pop()
return not stack