https://leetcode.com/problems/longest-valid-parentheses/
找到最长有效的左右括号组合
解法一:
栈
stack记录左括号位置,left记录当前遍历到的左括号数大于等于右括号数的位置
public class Solution {
public int longestValidParentheses(String s) {
if (s == null) {
return 0;
}
Stack<Integer> stack = new Stack();
int res = 0;
int left = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
if (stack.isEmpty()) {
left = i;
} else {
stack.pop();
if (stack.isEmpty()) {
res = Math.max(res, i - left);
} else {
res = Math.max(res, i - stack.peek());
}
}
}
}
return res;
}
}
dp数组记录以当前位置为结尾的有效parenthesis长度,下一位置的dp值在当前位置的有效parenthesis串的前一位i - dp[i - 1] - 1为"("时可以由递推公式递推得到。值为前一位置有效串长度 + 2 + (i - dp[i - 1] - 1的前一位的有效串长度)
public class Solution {
public int longestValidParentheses(String s) {
s = ")" + s;
int[] dp = new int[s.length()];
int res = 0;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == ')' && s.charAt(i - dp[i - 1] - 1) == '(') {
dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] - 2];
res = Math.max(res, dp[i]);
}
}
return res;
}
}