20 valid parentheses

AC and Best Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def (self, s):
"""
:type s: str
:rtype: bool
"""
def match(a,b):
if a == "(" and b == ")":
return True
if a == "[" and b == "]":
return True
if a == "{" and b == "}":
return True
return False
stack = []
for i in s:
if i == "(" or i == "[" or i == "{":
stack.append(i)
else:
if len(stack) > 0 and match(stack[-1],i):
stack.pop()
else:
return False
return stack == []

Time complexity: O(n)
Space Complexity: O(2)

if element in i is left bracket, push it
else return False if it not match last left bracket