Posted on

Description

Submission

class Solution {
public:
    int longestValidParentheses(string s) {
        vector<bool> cancel(s.size());
        stack<pair<char, int>> stk;
        for(int i = 0; i < s.size(); ++i) {
            cancel[i] = false;
            if(s[i] == '(') {
                stk.push(make_pair(s[i], i));
            } else {
                if(stk.empty()) continue;
                if(stk.top().first == '(') {
                    cancel[stk.top().second] = true;
                    cancel[i] = true;
                    stk.pop();
                }
            }
        }
        int count = 0;
        int maximum = 0;
        for(int i = 0; i < s.size(); ++i) {
            if(cancel[i] == true) count++;
            else {
                if(count > maximum) maximum = count;
                count = 0;
            }
        }

        return count > maximum ? count : maximum;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *