Longest Valid Parentheses Algorithm

The Longest Valid Parentheses Algorithm is a problem-solving approach designed to find the length of the longest valid parentheses substring in a given string. This algorithm can be implemented using various techniques, such as dynamic programming, stacks, or simple iterative traversal. The primary objective is to efficiently determine the longest sequence of well-formed, balanced parentheses within the input string, which can have a combination of open '(' and closed ')' brackets. One of the popular solutions to implement this algorithm is by using a stack data structure. First, initialize an empty stack and push -1 onto it to serve as a marker for the base. Next, iterate through the input string, and for each character, perform the following operations: if it is an open bracket '(', push its index onto the stack; if it is a closed bracket ')', pop an element from the top of the stack. If the stack is not empty after the pop operation, update the length of the longest valid parentheses substring by taking the maximum of the current length and the difference between the current index and the index at the top of the stack. If the stack is empty after the pop operation, push the current index onto the stack to serve as the new base marker. By the end of the iteration, the length of the longest valid parentheses substring will be determined.
class Solution {
public:
    int longestValidParentheses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int n = s.size();
        int max_valid = 0;
        int count_left = 0, valid_count = 0;
        
        for (int i = 0; i < n; i++) {
            if (s[i] == '(') {
                count_left += 1;
                valid_count += 1;
            } else {
                valid_count -= 1;
            }
            
            if (valid_count < 0) {
                valid_count = 0;
                count_left = 0;
            } else if (valid_count == 0) {
                max_valid = max(max_valid, count_left);
            }
        }
        
        valid_count = 0;
        int count_right = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (s[i] == ')') {
                count_right += 1;
                valid_count += 1;
            } else {
                valid_count -= 1;
            }
            
            if (valid_count < 0) {
                valid_count = 0;
                count_right = 0;
            } else if (valid_count == 0) {
                max_valid = max(max_valid, count_right);
            }
        }
        return 2 * max_valid;
    }
};

LANGUAGE:

DARK MODE: