File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed
Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change 1+ // CPP program to check for balanced parenthesis.
2+ #include < bits/stdc++.h>
3+ using namespace std ;
4+
5+ // function to check if paranthesis are balanced
6+ bool areParanthesisBalanced (string expr)
7+ {
8+ stack<char > s;
9+ char x;
10+
11+ // Traversing the Expression
12+ for (int i=0 ; i<expr.length (); i++)
13+ {
14+ if (expr[i]==' (' ||expr[i]==' [' ||expr[i]==' {' )
15+ {
16+ // Push the element in the stack
17+ s.push (expr[i]);
18+ continue ;
19+ }
20+
21+ // IF current current character is not opening
22+ // bracket, then it must be closing. So stack
23+ // cannot be empty at this point.
24+ if (s.empty ())
25+ return false ;
26+
27+ switch (expr[i])
28+ {
29+ case ' )' :
30+
31+ // Store the top element in a
32+ x = s.top ();
33+ s.pop ();
34+ if (x==' {' || x==' [' )
35+ return false ;
36+ break ;
37+
38+ case ' }' :
39+
40+ // Store the top element in b
41+ x = s.top ();
42+ s.pop ();
43+ if (x==' (' || x==' [' )
44+ return false ;
45+ break ;
46+
47+ case ' ]' :
48+
49+ // Store the top element in c
50+ x = s.top ();
51+ s.pop ();
52+ if (x ==' (' || x == ' {' )
53+ return false ;
54+ break ;
55+ }
56+ }
57+
58+ // Check Empty Stack
59+ return (s.empty ());
60+ }
61+
62+ // Driver program to test above function
63+ int main ()
64+ {
65+ string expr = " {()}[]" ;
66+
67+ if (areParanthesisBalanced (expr))
68+ cout << " Balanced" ;
69+ else
70+ cout << " Not Balanced" ;
71+ return 0 ;
72+ }
You can’t perform that action at this time.
0 commit comments