Created
November 1, 2020 14:10
-
-
Save swetarajbhar/f158d0c6be5ec2a4480d13370ce57e12 to your computer and use it in GitHub Desktop.
Check for balanced parentheses in an expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<stack> | |
using namespace std; | |
bool checkbalance(string expr) | |
{ | |
stack<char> s; | |
char x; | |
for(int i=0;i<expr.length();i++) | |
{ | |
if(expr[i]=='(' || expr[i] == '{' || expr[i] == '[') | |
{ | |
s.push(expr[i]); | |
} | |
if(s.empty()) | |
{ | |
return false; | |
} | |
switch(expr[i]) | |
{ | |
case ')': | |
x=s.top(); | |
s.pop(); | |
if(expr[i]== '}' || expr[i] == ']') | |
{ | |
return false; | |
} | |
break; | |
case '}': | |
x=s.top(); | |
s.pop(); | |
if(expr[i]== ')' || expr[i] == ']') | |
{ | |
return false; | |
} | |
break; | |
case ']' : | |
x=s.top(); | |
s.pop(); | |
if(expr[i]== '}' || expr[i] == ')') | |
{ | |
return false; | |
} | |
break; | |
} | |
} | |
return (s.empty()); | |
} | |
int main() | |
{ | |
string expr; | |
cout<<"Enter Expression : "; | |
cin>>expr; | |
if(checkbalance(expr)) | |
{ | |
cout<<"Balanced!"; | |
} | |
else | |
{ | |
cout<<" Not Balanced!"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment