public class Solution {
public int longestValidParentheses(String s) {
int[] f = new int[s.length()];
int ret = 0;
for(int i=1; i<s.length(); i++){
if(s.charAt(i)==')' && i-f[i-1]-1>=0 && s.charAt(i-f[i-1]-1)=='('){
f[i]=f[i-1]+2;
if(i-f[i]>0)
f[i] += f[i-f[i]];
}
ret = Math.max(ret, f[i]);
}
return ret;
}
}
思路:想了一下,遍历string 的时候每一次有效长度都可能变化,上一个的结果影响下一个的结果,但是不决定下一个的结果。因此,需要记录上一个位置的结果,在此基础上决定当前的值,知道走到string最后。这里面还有一点,如果中途括号顺序被破坏,那么需要重新计算。计算的值比较之前的最大值。
如果当前值的符号无效, f[n] = f[n-1]; 如果当前值的符号有效,f(
Given a string containing just the characters '('
and ')'
,
find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
,
which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring
is "()()"
, which has length = 4.