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.
本文介绍了一种求解字符串中最长有效括号子串长度的方法。通过动态规划记录每个位置的有效括号长度,并更新最大长度,实现高效查找。
150

被折叠的 条评论
为什么被折叠?



