-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20.valid-parentheses.py
59 lines (56 loc) · 1.62 KB
/
20.valid-parentheses.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# @lc code=start
class Solution:
def isValid(self, s: str) -> bool:
"""
'(', ')', '{', '}', '[' and ']'
Stack
T : O(N) 33.92% | 50ms
S : O(N) 69.47% | 13.9mb
"""
stack = []
for char in s:
if char in ['(', '{', '[']:
stack.append(char)
else:
if len(stack) == 0:
return False
elif stack[-1] == '(' and char == ')':
stack.pop()
elif stack[-1] == '{' and char == '}':
stack.pop()
elif stack[-1] == '[' and char == ']':
stack.pop()
else:
return False
return True if len(stack) != 0 else False
def isValid(self, s: str) -> bool:
"""
T : O(N) 19.71% | 57ms
S : O(N) 23.68% | 13.9mb
"""
stack = []
for char in s:
if char in ['(', '[', '{']:
stack.append(char)
else:
if len(stack) == 0:
return False
else:
if char == ')' and stack[-1] != '(':
return False
elif char == ']' and stack[-1] != '[':
return False
elif char == '}' and stack[-1] != '{':
return False
else:
stack.pop()
if len(stack) > 0:
return False
else:
return True
# @lc code=end