C++ with stack


  • 0
    G
    class Solution {
    public:
        bool isValid(string a_str) {
            stack<char> stk;
            for (int i = 0; i < a_str.length(); i++) {
                if (a_str.at(i) == '(' || a_str.at(i) == '{' || a_str.at(i) == '[') {
                    stk.push(a_str.at(i));
                }
                else if (a_str.at(i) == ')' || a_str.at(i) == '}' || a_str.at(i) == ']') {
                    if (stk.empty() || !isClosedCorrectly(stk.top(), a_str.at(i))) {
                        return false;
                    }
                    else {
                        stk.pop();
                    }
                }
            }
            if (stk.empty()) {
                return true;
            }
            return false;
        }
        bool isClosedCorrectly(char a_open, char a_close) {
            if (a_open == '(' && a_close == ')') return true;
            if (a_open == '{' && a_close == '}') return true;
            if (a_open == '[' && a_close == ']') return true;
            return false;
        }
    };

Log in to reply
 

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