-
-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy path20_Valid_parentheses.py
More file actions
21 lines (20 loc) · 791 Bytes
/
20_Valid_parentheses.py
File metadata and controls
21 lines (20 loc) · 791 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for i in range(len(s)):
if s[i] == "(" or s[i] == "[" or s[i] == "{": #check if an open bracket, push to stack
stack.append(s[i])
if s[i] == ")" or s[i] == "]" or s[i] == "}": #check if closing bracket, pop from stack and compare
if len(stack) == 0:
return False
prev = stack.pop()
if prev == "(" and s[i] != ")":
return False
if prev == "[" and s[i] != "]":
return False
if prev == "{" and s[i] != "}":
return False
if len(stack) == 0:
return True
else:
return False