Simple c++ solution using stack


  • 0
    Z
    bool isValid(string s) 
    {
        int end = 0;
        vector<char> check;
        
        for (int i=0; i<s.size(); i++)
        {
            end = check.size() - 1;
            switch(s[i])
            {
                case '(': 
                    check.push_back('(');
                    break;
                case ')':
                    if( check.size() == 0 || check[end] != '(' ) return false;
                    else check.pop_back();
                    break;
                case '{':
                    check.push_back('{');
                    break;
                case '}':
                    if( check.size() == 0 || check[end] != '{' ) return false;
                    else check.pop_back();
                    break;
                case '[':
                    check.push_back('[');
                    break;
                case ']':
                    if( check.size() == 0 || check[end] != '[' ) return false;
                    else check.pop_back();
                    break;
            }
        }
        if(check.size() != 0) return false;
        
        return true;

Log in to reply
 

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