Easy to understand solution with two stacks


  • 0
    T
    int longestValidParentheses(string s) {
        stack<int> indexes;
        stack<char> data;
        int result = 0;
        indexes.push(-1);
        data.push('#'); // anything but '('
        for (int i = 0; i < s.size(); i++) {
            char ch = s[i];
            if (ch == ')' && data.top() == '(') {
                indexes.pop();
                data.pop();
                result = max(result, i - indexes.top()); 
            } else {
                data.push(ch);
                indexes.push(i);
            }
        }
        return max(0, result);
    }

Log in to reply
 

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