Sudhanshu Shekhar
Sudhanshu Shekhar

Reputation: 15

Solution for Check Balanced Parenthesis is not working correctly

I was solving a 'check balanced parenthesis' problem in which I was expected to output "Success" if the parenthesis' were placed in the right order, and if the parenthesis' were mismatched, I have to output the 1-based index of the unmatched parenthesis in the string.

Here's my source code for the problem:

#include <iostream>
#include <stack>
#include <string>

using namespace std;

char get_pair_opening_bracket( char c );
int bracket_check( string &s );

char get_pair_opening_bracket( char c ){
    char o{};
    if( c==')' ){
        o= '(';
        return o;
    }
    else if( c=='}' ){
        o= '{';
        return o;
    }
    else if( c==']' ){
        o= '[';
        return o;
    }
}

int bracket_check(  string &s ){
    stack <char> brackets {};

    for( size_t i{}; i< s.size();++i ){
        if(( s[i]=='(') || ( s[i]== '[' ) || ( s[i]=='{' )){
            brackets.push(s.at(i));
        }
        else if(( s[i]==')') || ( s[i]== ']' ) || ( s[i]=='}' )){
            if( (brackets.empty()==true) || (brackets.top()!=get_pair_opening_bracket(s[i]) )){ 
                return (i+1) ; // problem here
            }
            else{
                brackets.pop();
            }
        
        }
    }
    if( brackets.empty()==true ){
        return 0;
    }
}

int main(){
    string s{};
    getline(cin,s);

    bool check{};
    check= bracket_check(s);

    if( check ==0 ){
        cout<<"Success"<<endl;
    }
    else{
        cout<<check<<endl;
    }

    return 0;
} 

I have commented on the line where I feel the problem lies, which is causing the program to always output '1' in case of mismatched parenthesis. So, please help me with the bug .....

Upvotes: 0

Views: 64

Answers (1)

john
john

Reputation: 87959

Actually I think the main problem is here

bool check{};
check= bracket_check(s);

You assign the integer return value to a boolean. So not surprisingly you only get 0 or 1 for an answer.

You have other problems, more instance what is your function going to return if the input is "("?

Incidentally I see this style quite a lot size_t i{};. What's wrong with size_t i = 0;? It's a lot easier to understand for an old-timer like me.

Upvotes: 1

Related Questions