My 0ms C++ solution with explaination


  • 0
    C

    Using stack.
    And a map 'correspond' to transverse the character to numbers for easier check, in this way we just need to 1)check whether the number is less than 3 to determine it is left or right; 2) check whether the difference is 3 to determine whether they are valid brackets.

    class Solution {
    public:
        bool isValid(string s) {
            int L = s.length();
            if( L&1==1 )
                return false;
            
            map<char,int> correspond;
            correspond['\('] = 0;
            correspond['\['] = 1;
            correspond['\{'] = 2;
            correspond['\)'] = 3;
            correspond['\]'] = 4;
            correspond['\}'] = 5;
            
            stack<char> brackets;
            for( int i = 0; i<L; i++ ){
                if( correspond[s[i]] <3 )
                    brackets.push(correspond[s[i]]);
                else{
                    if( brackets.empty() || correspond[s[i]]!=brackets.top()+3 )
                        return false;
                    brackets.pop();
                }
            }
            return brackets.empty();
        }
    };

Log in to reply
 

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