-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathbalancedParenthesisusingStack.cpp
80 lines (57 loc) · 1.31 KB
/
balancedParenthesisusingStack.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//Checking for balancing parenthesis- implementation using stacks
#include<iostream>
#include<stack>
#include<string>
using namespace std;
//function to check whether a given expression has balanced parenthesis or not?
bool checkBalance(string exp) {
stack<char>S;//defining a char stack
//scanning left to right of the expression
for(int i=0;i<exp.length();i++) {
switch(exp[i]) {
//if opening brace then push them to stack
case '{' :
case '(' :
case '[' :
S.push(exp[i]);
break;
case '}' :
if(S.top()=='{' && !S.empty()) {
S.pop();
}
break;
case ']' :
if(S.top()=='[' && !S.empty()) {
S.pop();
}
break;
case ')' :
if(S.top()=='(' && !S.empty()) {
S.pop();
}
break;
}
}
//coming out of loop after reading the complete expression
//now we have to check if the stack is empty of not?
return S.empty() ? true : false;
// if(!S.empty()) {
// cout<<endl<<"Unbalanced expression"<<endl;
//
// }
// //if stack is empty -then the expression is balanced
// else {
// cout<<endl<<"Stack is Empty, hence balanced expression"<<endl;
// }
}
int main () {
string exp;
cin>>exp;
if(checkBalance(exp)) {
cout<<"Balanced expression"<<endl;
}
else {
cout<<"unbalanced expression"<<endl;
}
return 0;
}