-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_valid_parentheses.py
More file actions
39 lines (33 loc) · 1.04 KB
/
20_valid_parentheses.py
File metadata and controls
39 lines (33 loc) · 1.04 KB
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
31
32
33
34
35
36
37
38
39
# https://leetcode.com/problems/valid-parentheses/
class Solution:
def isValid(self, s: str) -> bool:
from collections import deque
stack = deque()
for char in s:
if char == '(' or char == '[' or char == '{':
stack.append(char)
else:
if stack:
if char == ')' and stack.pop() != '(':
return False
elif char == ']' and stack.pop() != '[':
return False
elif char == '}' and stack.pop() != '{':
return False
else:
return False
if stack:
return False
return True
class Solution:
def isValid(self, s: str) -> bool:
d = {'(':')', '{':'}','[':']'}
stack = []
for i in s:
if i in d:
stack.append(i)
elif len(stack) == 0 or d[stack.pop()] != i:
return False
return len(stack) == 0
# T = O(N)
# S = O(N)