Skip to content

Commit 73dcdd8

Browse files
committed
Balanced parenthesis problem (using Stack) - C++
1 parent fbe3dcf commit 73dcdd8

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
bool balanced(string str){
5+
stack<char> s;
6+
for(int i=0; i<str.length(); i++){
7+
if(str[i] == '{' || str[i] == '(' || str[i] == '[')
8+
s.push(str[i]);
9+
else if(!s.empty() && (str[i] == '}' && s.top() == '{')|| (str[i] == ')' && s.top() == '(') || (str[i] == ']' && s.top() == '['))
10+
s.pop();
11+
else
12+
return false;
13+
}
14+
15+
return s.empty();
16+
}
17+
int main(){
18+
//An application on how stack can be useful to check standard Balanced bracket problem
19+
string str;
20+
char choice;
21+
do{
22+
cin>>str;
23+
(balanced(str))?cout<<"Balanced":cout<<"Not Balanced";
24+
cout<<"\nDo you want to try again?(y/n) ";
25+
cin>>choice;
26+
}while(choice != 'n');
27+
return 0;
28+
}

0 commit comments

Comments
 (0)