File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Stack :
2
+ def __init__ (self ):
3
+ self .items = []
4
+
5
+ def push (self , item ):
6
+ self .items .append (item )
7
+
8
+ def pop (self ):
9
+ return self .items .pop ()
10
+
11
+ def is_empty (self ):
12
+ return self .items == []
13
+
14
+ def peek (self ):
15
+ return self .items [- 1 ]
16
+
17
+ def display (self ):
18
+ return self .items
19
+
20
+ def is_same (p1 , p2 ):
21
+ if p1 == '(' and p2 == ')' :
22
+ return True
23
+ elif p1 == '[' and p2 == ']' :
24
+ return True
25
+ elif p1 == '{' and p2 == '}' :
26
+ return True
27
+ else :
28
+ return False
29
+
30
+ def is_balanced (check_string ):
31
+ s = Stack ()
32
+ index = 0
33
+ is_bal = True
34
+ while index < len (check_string ) and is_bal :
35
+ paren = check_string [index ]
36
+ if paren in '{[(' :
37
+ s .push (paren )
38
+ else :
39
+ if s .is_empty ():
40
+ is_bal = False
41
+ else :
42
+ top = s .pop ()
43
+ if not is_same (top , paren ):
44
+ is_bal = False
45
+ index += 1
46
+
47
+ if s .is_empty () and is_bal :
48
+ return True
49
+ else :
50
+ return False
51
+
52
+
53
+ print (is_balanced ('[((())})]' ))
You can’t perform that action at this time.
0 commit comments