C++ simple one stack solution


  • 0
    J

    '''

    int getV(char c)
    {
        if (c == '(') return 1;
        else if (c == ')') return -1;
        else if (c == '[') return 2;
        else if (c == ']') return -2;
        else if (c == '{') return 3;
        else if (c == '}') return -3;
        else return 0;
    }
    
    bool isValid(string s) {
        stack<int> st;
        for (int i = 0; i < s.size(); i++)
        {
            int v = getV(s[i]);
            if (v < 0)
            {
                if (st.empty()) return false;
                if (st.top() + v) return false;
                st.pop();
            }
            else
            {
                st.push(v);
            }
        }
        
        return st.empty();
    }
    

    '''


Log in to reply
 

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