File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
data_structures/5_Stack/Exercise Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ #added Chengfeng's solution at the end
12from collections import deque
23
34class Stack :
@@ -49,3 +50,27 @@ def is_balanced(s):
4950 print (is_balanced ("((a+g))" ))
5051 print (is_balanced ("))" ))
5152 print (is_balanced ("[a+b]*(x+2y)*{gg+kk}" ))
53+
54+ # Below is Chengfeng's solution. I tested and it worked.
55+ def is_balanced (s ):
56+ dict = {"{" :"}" ,"(" :")" ,"[" :"]" }
57+ stack = Stack ()
58+ push_count = 0
59+ for char in s :
60+ if char in dict .keys ():
61+ stack .push (char )
62+ push_count += 1
63+ elif char in dict .values () and stack .size ()!= 0 :
64+ stack .pop ()
65+ if push_count != 0 and stack .size ()== 0 :
66+ return True
67+ else :
68+ return False
69+
70+ if __name__ == '__main__' :
71+ print (is_balanced ("({a+b})" ))
72+ print (is_balanced ("))((a+b}{" ))
73+ print (is_balanced ("((a+b))" ))
74+ print (is_balanced ("((a+g))" ))
75+ print (is_balanced ("))" ))
76+ print (is_balanced ("[a+b]*(x+2y)*{gg+kk}" ))
You can’t perform that action at this time.
0 commit comments