-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_paranthesis.py
More file actions
50 lines (43 loc) · 1.24 KB
/
valid_paranthesis.py
File metadata and controls
50 lines (43 loc) · 1.24 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
class Solution:
def isValid(self, s):
stack = []
for char in s:
if char == "(" or char == "{" or char == "[":
stack.append(char)
else:
if len(stack) == 0:
return False
last = stack.pop()
if last == "(" and char != ")":
return False
if last == "{" and char != "}":
return False
if last == "[" and char != "]":
return False
if len(stack) != 0:
return False
else:
return True
def isValid2(self, s):
stack = []
pairs = {"(": ")", "{": "}", "[": "]"}
for char in s:
if char in pairs:
stack.append(char)
else:
if len(stack) == 0:
return False
last = stack.pop()
if pairs[last] != char:
return False
if len(stack) > 0:
return False
else:
return True
def main():
sol = Solution()
res1 = sol.isValid("[]({})")
res2 = sol.isValid2("[{(}]")
print(res1, res2)
if __name__ == "__main__":
main()