Simple stack-map solution


  • 1
    A
        map<char, char> tab;
        tab.insert(make_pair('(', ')'));
        tab.insert(make_pair('[', ']'));
        tab.insert(make_pair('{', '}'));
        
        stack<char> brackets;
        char brack;
        for (int i = 0; i < s.length(); ++i) {
            brack = s[i];
            if (brack == '(' || brack == '[' || brack == '{') {
                brackets.push(tab[brack]);
                continue;
            }
            if (brack == ')' || brack == ']' || brack == '}') {
                if (!brackets.empty() && brack == brackets.top())
                    brackets.pop();
                else
                    return false;
             }
        }
        return brackets.empty();

Log in to reply
 

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