-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_valid_parentheses.py
More file actions
59 lines (47 loc) · 1.56 KB
/
20_valid_parentheses.py
File metadata and controls
59 lines (47 loc) · 1.56 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Topics:
- two pointers
"""
class Solution:
"""
Inefficient O(N^2) because python string slicing uses a list
Valid if:
- Every open bracket is closed by the same type of close bracket.
- Open brackets are closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Ideas
- recursive function that can go inside each bracket pair and see if there is another bracket pair
- pointers that find each left brack and look for right one cheking for invalid conditions in between
- hash map counting each type of bracket
- reversed should be equal to ordinay
"(){}[]"
^^
{[]}
"""
def isValid(self, s: str) -> bool:
pairs = {
")":"(",
"}":"{",
"]":"[",
}
if len(s) % 2 != 0: # if string len is odd then invalid
return False
stack = []
for char in s:
if not char in pairs:
stack.append(char)
else:
if not stack:
return False
if pairs[char] != stack[-1]:
return False
else:
stack.pop()
return False if stack else True
solution = Solution()
print(solution.isValid("((")) # false
print(solution.isValid("[")) # false
print(solution.isValid("]]")) # false
print(solution.isValid("{[]}")) # true
print(solution.isValid("[(])")) # false
print(solution.isValid("(){}[]")) # true