Skip to main content

Balanced Parenthesis in C++


 #include<bits/stdc++.h>
#include<time.h>
using namespace std;
bool isvalid(string s){
 
    stack<char> st;
    bool ans = true;
    for(int i=0;i<s.size();i++){
        if(s[i] == '{' or s[i] == '(' or s[i] == '['){
            st.push(s[i]);
        }
        else if(s[i]==')'){
        if(!st.empty() and st.top()== '('){
            st.pop();
        }
        else{
            ans = false;
            break;
        }
   
    }
    else if(s[i]==']'){
        if(!st.empty() and st.top()== '['){
            st.pop();
        }
        else{
            ans = false;
            break;
        }
   
    }
    else if(s[i]=='}'){
        if(!st.empty() and st.top()== '{'){
            st.pop();
        }
        else{
            ans = false;
            break;
        }
   
    }

    }

    if(!st.empty())
        return false;  
        return ans;
         
   
}
int main()
{
    string s = "{[()]}";
    time_t t1,t2;
    time(&t1);
    cout<<"Check Balanced Parenthesis"<<endl;
    // cout<<"Enter the Parenthesis"<<endl;
    // cin>>s;
    if(isvalid(s)){
        cout<<"\nValid string\n"<<endl;

    }
    else{
        cout<<"\nInvalid String\n"<<endl;
    }
    time(&t1);
    double t = (t2=t1);
    cout<<"Taken time to execute "<<t<<" sec"<<endl;
    return 0;
}

Comments