Longest Valid Parentheses in Python

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        """
        This function finds the length of the longest valid (well-formed) parentheses substring.

        :param s: A string containing just the characters '(' and ')'
        :return: The length of the longest valid parentheses substring
        """

        # Initialize a stack to keep track of the indices of opening parentheses
        stack = [
            -1
        ]  # Start with -1 to handle the edge case of a valid string from the beginning

        # Variable to keep track of the length of the longest valid parentheses substring
        max_length = 0

        # Iterate over each character in the string
        for i, char in enumerate(s):
            if char == "(":
                # If the character is an opening parenthesis, push its index onto the stack
                stack.append(i)
            else:
                # If the character is a closing parenthesis, pop from the stack
                stack.pop()

                # If the stack is empty after popping, push the current index onto the stack
                # This marks the beginning of a new potential valid substring
                if not stack:
                    stack.append(i)
                else:
                    # If the stack is not empty, calculate the length of the current valid substring
                    # Subtract the current index with the top index in the stack
                    current_length = i - stack[-1]

                    # Update the max_length if the current length is greater
                    max_length = max(max_length, current_length)

        return max_length

PrevNext