-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalid-parentheses.py
More file actions
30 lines (23 loc) · 909 Bytes
/
valid-parentheses.py
File metadata and controls
30 lines (23 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# https://leetcode.com/problems/valid-parentheses/
# Related Topics: String, Stack
# Difficulty: Easy
# Initial thoughts:
# Creating a lookup table for all the types of parentheses and
# using a stack we touch every element of the input string and
# if it's an opening parenthes push it on the stack and if its
# a closing parenthes we pop one from the stack checking if it's
# a valid counterpart for the current parenthes.
# At the end, the stack must be empty
# Time complexity: O(n) where n === s.length
# Space complexity: O(n) where n === s.length
class Solution:
def isValid(self, s: str) -> bool:
lookup = {"(": ")", "[": "]", "{": "}"}
stack = []
for p in s:
if p in lookup:
stack.append(lookup[p])
else:
if len(stack) == 0 or stack.pop() != p:
return False
return len(stack) == 0