Sunday, 13 December 2015

Check Balanced Parenthesis in an Expression Using Stack API in C++

#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;
}

1 comment: