Simple solution. Use array to do comparisons.


  • 0
    P
    class Solution {
    public:
        bool isValid(string s) {
            stack<char>st;
            char k[256];
            k[(int)')'] = '(';
            k[(int)']'] = '[';
            k[(int)'}'] = '{';
            st.push('0');
            for(auto x : s)
            {
                if(x == '(' || x == '{' || x == '[')
                {
                     st.push(x);
                    continue;
                }
                if(st.top() == k[x]) {st.pop();}
                else return false;
            }
            st.pop();
            return (st.empty());
        }
    };

Log in to reply
 

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