-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_is_balanced.py
51 lines (39 loc) · 1.08 KB
/
stack_is_balanced.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
from collections import deque
class Stack:
def __init__(self):
self.container = deque()
def push(self, val):
self.container.append(val)
def pop(self):
return self.container.pop()
def peek(self):
return self.container[-1]
def is_empty(self):
return len(self.container) == 0
def size(self):
return len(self.container)
def is_match(ch1, ch2):
match_dict = {
')': '(',
']': '[',
'}': '{'
}
return match_dict[ch1] == ch2
def is_balanced(s):
stack = Stack()
for ch in s:
if ch=='(' or ch=='{' or ch == '[':
stack.push(ch)
if ch==')' or ch=='}' or ch == ']':
if stack.size()==0:
return False
if not is_match(ch,stack.pop()):
return False
return stack.size()==0
if __name__ == '__main__':
print(is_balanced("({a+b})"))
print(is_balanced("))((a+b}{"))
print(is_balanced("((a+b))"))
print(is_balanced("((a+g))"))
print(is_balanced("))"))
print(is_balanced("[a+b]*(x+2y)*{gg+kk}"))