1. 题目
2. 思路
(1) 栈
- 栈中存放的是左括号的下标,若遇到右括号,则弹出与其匹配的最近的左括号,同时更新匹配的长度。
3. 代码
import java.util.Deque;
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int longestValidParentheses(String s) {
char[] chars = s.toCharArray();
int n = chars.length;
Deque<Integer> stack = new LinkedList<>();
stack.push(-1);
int res = 0;
for (int i = 0; i < n; i++) {
if (chars[i] == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
res = Math.max(res, i - stack.peek());
}
}
}
return res;
}
}