32. Longest Valid Parentheses

Description

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 3 * 104

  • s[i] is '(', or ')'.

Tags

String, Dynamic Programming

Solution

We make use of 2 counters l and r to count '(' and ')'. We iterate through the string twice, once from left to right, and once the other way around. Whenever left becomes equal to right, we calculate the length of the current valid string and keep track of maximum length substring found so far. In the forward traversal, if right becomes greater than left we reset left and right to 0, vice versa.

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(1)O(1)

Code

func longestValidParentheses(s string) int {
	var ans, l, r int
	for i := 0; i < len(s); i++ {
		if s[i] == '(' {
			l++
		} else {
			r++
		}
		if l == r && l+r > ans {
			ans = l + r
		} else if r > l {
			l, r = 0, 0
		}
	}
	l, r = 0, 0
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == '(' {
			l++
		} else {
			r++
		}
		if l == r && l+r > ans {
			ans = l + r
		} else if r < l {
			l, r = 0, 0
		}
	}
	return ans
}

Reference

Last updated

Was this helpful?