Skip to content

Commit 85ef569

Browse files
committed
valid parentheses solution
1 parent 1aabf5b commit 85ef569

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

valid-parentheses/jylee2033.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
close_to_open = {')': '(', '}': '{', ']': '['}
4+
stack = [] # Open brackets
5+
6+
if len(s) % 2 == 1:
7+
return False
8+
9+
for ch in s:
10+
# Open bracket
11+
if ch in close_to_open.values():
12+
stack.append(ch)
13+
# Close bracket
14+
else:
15+
if len(stack) == 0:
16+
return False
17+
18+
expected = close_to_open[ch]
19+
if stack.pop() != expected:
20+
return False
21+
22+
return len(stack) == 0
23+
24+
# Time Complexity: O(n)
25+
# Space Complexity: O(n)

0 commit comments

Comments
 (0)