Skip to content

Instantly share code, notes, and snippets.

@swetarajbhar
Created November 1, 2020 14:10
Show Gist options
  • Save swetarajbhar/f158d0c6be5ec2a4480d13370ce57e12 to your computer and use it in GitHub Desktop.
Save swetarajbhar/f158d0c6be5ec2a4480d13370ce57e12 to your computer and use it in GitHub Desktop.
Check for balanced parentheses in an expression
#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