1.题目描述
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
给定一个只包含 '('
和 ')'
的字符串,找出最长的包含有效括号的子串的长度。
Example 1:
Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Example 2:
Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”
2.Solutions
This is my DP solution, just one pass
V[i] represents number of valid parentheses matches from S[j to i] (j<i)
V[i] = V[i-1] + 2 + previous matches V[i- (V[i-1] + 2) ] if S[i] = ‘)’ and ‘(‘ count > 0
1 | public int longestValidParentheses(String s) { |
The idea is simple, we only update the result (max) when we find a “pair”.
If we find a pair. We throw this pair away and see how big the gap is between current and previous invalid.
EX: “( )( )”
stack: -1, 0,
when we get to index 1 “)”, the peek is “(“ so we pop it out and see what’s before “(“.
In this example it’s -1. So the gap is “current_index” - (-1) = 2.
The idea only update the result (max) when we find a “pair” and push -1 to stack first covered all edge cases.
1 | public int longestValidParenthesesUseStack(String s) { |