Help me compare which one is more reasonable?


  • 0
    Z

    At first,I think valid parentheses means brace,bracket,parentheses must use accord to their priority level,for example:
    {()()[()]}is valid,but ([]) is invalid
    and I write code as follow

    bool isValid(string s) {
        int small = 0,mid = 0,big = 0;
        for( string::iterator it = s.begin();it != s.end();++it )   {
            if( *it == '(' )    
                small++;
            else if( *it == '[' )   {
                if( small )
                    return false;
                else    
                    mid++;
            }
            else if( *it == '{' )   {
                if( small || mid )  
                    return false;
                else 
                    big++;
            }
            else if( *it == ')' )   {
                if( !small )
                    return false;
                else
                    --small;
            }
            else if( *it == ']' )   {
                if( small || !mid ) 
                    return false;
                else
                    --mid;
            }
            else {
                if( small || mid || !big )
                    return false;
                else
                    --big;
            }
        }
        if( small || mid || big )   return false;
        return true;
    }
    

    but it returns wrong.
    then i realize this problem don't concern about this point,so change it to this

    bool isValid(string s) {
        stack<int> stk;
        stk.push(0);
        for( string::iterator it = s.begin();it != s.end();++it )   {
            if( *it == '(' )    
                stk.push(1);
            else if( *it == '[' )
                stk.push(2);
            else if( *it == '{' )
                stk.push(3);
            else if( *it == ')' )   {
                if( stk.top() == 1 )
                    stk.pop();
                else
                    return false;
            }
            else if( *it == ']' )   {
                if( stk.top() == 2 )    
                    stk.pop();
                else 
                    return false;
            }
            else if( *it == '}' )   {
                if( stk.top() == 3 )
                    stk.pop();
                else
                    return false;
            }
        }
        if( stk.top() == 0 )    return true;
        return false;
    }
    

    though this time it is right,I really doubt if it is reasonable?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.