Another 0ms C++ solution


  • 0
    I
    class Solution {
    public:
        bool isValid(string s) {
            if (s.empty() || s.size() % 2 == 1) return false;
    
            std::vector<int> v;
            v.resize(128);
            v['('] = 1;
            v[')'] = -1;
            v['{'] = 2;
            v['}'] = -2;
            v['['] = 3;
            v[']'] = -3;
    
            std::deque<int> q;
            q.push_back(0);
            
            for (int i = 0; i < s.size(); ++i) {
                int x = v[s[i]];
                if (x > 0) {
                    q.push_back(x);
                } else {
                    if (q.back() != -x) return false;
                    q.pop_back();
                }
            }
    
            return q.back() == 0;
        }
    };

Log in to reply
 

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