2026-01-07 14:29:52 +0300 MSK

Longest Valid Parentheses

Code

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        stack = []
        lengths = [0] * len(s)
        max_length = 0
        for i, char in enumerate(s):
            stack.append((i, char))
            while len(stack) > 1 and stack[-2][1] == "(" and stack[-1][1] == ")":
                start, end = stack[-2][0], stack[-1][0]
                length = end - start + 1
                if start > 1:
                    length += lengths[start - 1]
                lengths[end] = length
                max_length = max(max_length, length)
                stack.pop()
                stack.pop()

        return max_length