
栈
栈里面存下标 ,栈底放初始哨兵 -1,用来计算长度:
- 遇到
(:下标入栈 - 遇到
):弹出栈顶
-
-
如果栈空了:把当前下标压入,作为新哨兵
-
如果栈不为空:当前下标 - 栈顶下标 = 当前有效括号长度,更新最大值
class Solution {
public int longestValidParentheses(String s) {
Dequestack = new LinkedList<>();
stack.push(-1); // 哨兵
int maxLen = 0;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c == '('){
stack.push(i);
}else{
stack.pop();
if(stack.isEmpty()){
stack.push(i);
}else{
maxLen = Math.max(maxLen, i - stack.peek());
}
}
}
return maxLen;
}
}
-
动态规划
dp[i]:以 i 位置结尾的最长有效括号长度
- si =
(:dp i=0,以左括号结尾不可能合法 - si =
):
-
- si-1 =
(→dp[i] = dp[i-2] + 2 - si-1 =
),并且i - dp[i-1] - 1 >=0且s[i-dp[i-1]-1] == '('→dp[i] = dp[i-1] + 2 + dp[i - dp[i-1] - 2]
class Solution {
public int longestValidParentheses(String s) {
int n = s.length();
int[] dp = new int[n];
int max = 0;
for(int i = 1; i < n; i++){
if(s.charAt(i) == ')'){
if(s.charAt(i-1) == '('){
dp[i] = (i >= 2 ? dp[i-2] : 0) + 2;
}else{
int pre = i - dp[i-1] - 1;
if(pre >= 0 && s.charAt(pre) == '('){
dp[i] = dp[i-1] + 2 + (pre > 0 ? dp[pre - 1] : 0);
}
}
max = Math.max(max, dp[i]);
}
}
return max;
}
} - si-1 =
双指针
左指针统计左括号数量,右指针统计右括号:
- 从左往右扫:右 > 左时清零;相等时计算长度
- 从右往左扫:左 > 右时清零;相等时计算长度
弥补单向扫描漏掉的情况,比如 (() 左扫算不出,右扫可以抓到
class Solution {
public int longestValidParentheses(String s) {
int left = 0, right = 0, max = 0;
// 左到右
for(char c : s.toCharArray()){
if(c == '(') left++;
else right++;
if(left == right) max = Math.max(max, left + right);
else if(right > left) left = right = 0;
}
left = right = 0;
// 右到左
for(int i = s.length()-1; i >=0; i--){
char c = s.charAt(i);
if(c == '(') left++;
else right++;
if(left == right) max = Math.max(max, left + right);
else if(left > right) left = right = 0;
}
return max;
}
}