#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
bool isSame(char ch,char arr){
if(ch=='('&&arr==')'||ch==')'&&arr=='(')
return true;
else if(ch=='{'&&arr=='}'||ch=='}'&&arr=='{')
return true;
else if(ch=='['&&arr==']'||ch==']'&&arr=='[')
return true;
else
return false;
}
bool Check(char *p){
stack <char> s;
for(int i=0;i<strlen(p);i++){
if(p[i]=='('||p[i]=='{'||p[i]=='['){
s.push(p[i]);
}
else if(p[i]==')'||p[i]=='}'||p[i]==']'){
if(s.empty())
return false;
char ch=s.top();
if(isSame(ch,p[i])){
s.pop();
}
else{
return false;
}
}
else{
continue;
}
}
if(s.empty())
return true;
else
return false;
}
int main()
{
char str[]="{A+(Q-T)+Z-M*(D+P)-Q/O}";
if(Check(str))
cout<<"Paranthesis is Balanced\n";
else
cout<<"Not Balanced\n";
return 0;
}
Sunday, 13 December 2015
Check Balanced Parenthesis in an Expression Using Stack API in C++
Subscribe to:
Post Comments (Atom)
Very informative article.Thank you author for posting this kind of article .
ReplyDeletehttp://www.wikitechy.com/view-article/java-program-to-check-for-balanced-parenthesis-by-using-stacks
Both are really good,
Cheers,
Venkat