-
Notifications
You must be signed in to change notification settings - Fork 0
/
20_valid_parentheses.py
84 lines (71 loc) · 2.04 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
---
title: Valid parentheses
number: 20
difficulty: easy
tags: ['String','Stack']
solved: true
---
"""
"""
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
"""
ROUND_BRACKETS = ['(',')']
SQUARE_BRACKETS = ['[',"]"]
CURLY_BRACKETS = ['{','}']
class Solution:
def isValid(self, s: str) -> bool:
return self.efficient(s)
def efficient(self,string:str):
stack = []
closed = {
")":"(","]":'[',"}":'{'
}
for char in string:
if char in closed:
if stack and stack[-1] == closed[char]:
stack.pop()
else:
return False
else:
stack.append(char)
return True if not stack else False
def simple(self,string:str):
types = {
"(": 0,")":0,
"[":1,"]":1,
"{":2,"}":2
}
valid = {
"(": ")",
"[":"]",
"{": "}"
}
stack = []
for item in string:
if len(stack) == 0:
stack.append(item)
else:
last_elem = stack[len(stack)-1]
last_type = types[last_elem]
current_type = types[item]
if last_type != current_type:
stack.append(item)
else:
if item == last_elem:
stack.append(item)
elif last_elem in valid and valid[last_elem] == item:
stack.pop()
else:
stack.append(item)
if len(stack) ==0:
return True
else:
return False
if __name__ == '__main__':
test = "()]["
print(Solution().isValid(test))