解题思路:
栈
class Solution {
public int longestValidParentheses(String s) {
int max = 0;
// 也可以使用 Stack<Integer> stack=new Stack<>();但Stack是遗留类,不推荐
Deque<Integer> stack = new LinkedList<>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) stack.push(i);
else max = Math.max(max, i - stack.peek());
}
}
return max;
}
}