public class Solution {
public int longestValidParentheses(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int len = s.length();
int max = 0;
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i < len; i++){
if(s.charAt(i) == '(')
stack.push(i);
else{
if(!stack.empty() && s.charAt(stack.peek()) == '('){
stack.pop();
if(stack.empty())
max = Math.max(max, i + 1);
else{
max = Math.max(max, i - stack.peek());
}
}
else
stack.push(i);
}
}
return max;
}
}Same idea. Using arrays instead of a stack.
public class Solution {
public int longestValidParentheses(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if (s == null || s.length() == 0)
return 0;
int l = s.length();
int dp[] = new int[l];
int max = 0, j;
for (int i = 1; i < l; i++) {
if (s.charAt(i) == ')') {
j = i - 1 - dp[i - 1];
if (j >= 0 && s.charAt(j) == '(')
dp[i] = i - j + 1 + ((j > 0) ? dp[j - 1] : 0);
}
if (dp[i] > max)
max = dp[i];
}
return max;
}
}

本文介绍了一种使用栈和动态规划方法求解最长有效括号序列的问题。通过两种不同的实现方式,展示了如何高效地找到字符串中包含的最大长度的有效括号子串。
350

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



