-
Notifications
You must be signed in to change notification settings - Fork 495
/
Copy pathBracket_Balancing_using_Stack.cpp
45 lines (45 loc) Β· 1.52 KB
/
Bracket_Balancing_using_Stack.cpp
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
#include<iostream>
#include<stack>
using namespace std;
bool isBalanced(string expr) {
stack<char> s;
char ch;
for (int i=0; i<expr.length(); i++) { //for each character in the expression, check conditions
if (expr[i]=='('||expr[i]=='['||expr[i]=='{') { //when it is opening bracket, push into stack
s.push(expr[i]);
continue;
}
if (s.empty()) //stack cannot be empty as it is not opening bracket, there must be closing bracket
return false;
switch (expr[i]) {
case ')': //for closing parenthesis, pop it and check for braces and square brackets
ch = s.top();
s.pop();
if (ch=='{' || ch=='[')
return false;
break;
case '}': //for closing braces, pop it and check for parenthesis and square brackets
ch = s.top();
s.pop();
if (ch=='(' || ch=='[')
return false;
break;
case ']': //for closing square bracket, pop it and check for braces and parenthesis
ch = s.top();
s.pop();
if (ch =='(' || ch == '{')
return false;
break;
}
}
return (s.empty()); //when stack is empty, return true
}
int main() {
string expr;
cin>>expr;
if (isBalanced(expr))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}