You are given a string containing just the characters '(' and ')'. Your task is to find the length of the longest valid (well-formed) parentheses substring.
Constraints:
'(' and ')'.Examples:
Input: ((())))
Output: 2
Explanation: The longest valid parentheses substring is (), which has a length of 2.
Input: ((()))
Output: 2
Explanation: The longest valid parentheses substring is (), which has a length of 2.
Input: )()()
Output: 4
Explanation: The longest valid parentheses substring is ()(), which has a length of 4.
Hints:
')', check if the top of the stack is a '('. If it is, pop the stack and calculate the length of the valid substring.'(', push the current index onto the stack.Solution: `python class Solution: def longestValidParentheses(self, s: str) -> int: max_len = 0 stack = [-1] # Initialize stack with -1 to handle edge cases
for i, char in enumerate(s):
if char == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_len
`
Explanation:
'(', we push its index onto the stack.')', we pop the top index from the stack. If the stack is empty after popping, we push the current index onto the stack.This solution has a time complexity of O(n) and a space complexity of O(n), where n is the length of the input string.