题解:
- 合法子串中num('(') > num(')') 左右括号的数量相等
- 合法序列的前缀 num('(') >= num(')') 左括号的序列要大于右括号的序列
- 如果出现 num('(') < num(')') 则说明这个右括号开始是不合法的,可以从该右括号为起点,重新遍历后面的子串
class Solution {
public int longestValidParentheses(String s) {
char[] ch = s.toCharArray();
int n = s.length();
if (n == 0) return 0;
Deque<Integer> stack = new ArrayDeque<>();
int res = 0;
for (int i = 0, start = -1; i < n; i++) {
if (ch[i] == '(') {
stack.push(i);
} else {
if (stack.size() > 0) {
stack.pop();
if (stack.size() > 0) {
res = Math.max(res, i - stack.peek());
} else {
res = Math.max(res, i - start);
}
} else {
start = i;
}
}
}
return res;
}
}
标签:start,int,32,最长,括号,num,res,stack
From: https://www.cnblogs.com/eiffelzero/p/16864289.html