-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack-BalancedParanthesis.cpp
More file actions
40 lines (39 loc) · 973 Bytes
/
stack-BalancedParanthesis.cpp
File metadata and controls
40 lines (39 loc) · 973 Bytes
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
#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <string.h>
#include <iostream>
using namespace std;
bool Pair (char openingBracket, char closingBracket) {
if(openingBracket == '(' && closingBracket == ')') return true;
else if(openingBracket == '{' && closingBracket == '}') return true;
else if(openingBracket == '[' && closingBracket == ']') return true;
return false;
}
bool BalancedParanthesis(string s) {
stack<char>s1;
for(int i=0;i<s.length();i++) {
if(s[i] == '{' || s[i] == '(' || s[i] == '[') {
s1.push(s[i]);
}
else if (s[i] == '}' || s[i] == ')' || s[i] == ']') {
if(s1.empty() || !Pair(s1.top(),s[i])) {
return false;
} else {
s1.pop();
}
}
}
return s1.empty() ? true : false;
}
int main(void) {
string s;
cout<<"pass the parenthesis expression: "<<endl;
cin>>s;
if(BalancedParanthesis(s)) {
cout<<"Balanced"<<endl;
} else {
cout<<"Unbalanced"<<endl;
}
return 0;
}