32. Longest Valid Parentheses
直接在stack中push括号的话不可以分辨留在栈中的括号的index,所以push每个符号的index。
栈中需要留一个-1来计算都是完整括号的状况,因为-1一直在栈中所以需要stack.size() > 1,否则会溢出。
public int longestValidParentheses(String s) {
int res = 0;
LinkedList<Integer> stack = new LinkedList<>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ')' && stack.size() > 1 && s.charAt(stack.peek()) == '(') {
stack.pop(); // pop '(' index in the stack
res = Math.max(res, i - stack.peek());
} else {
stack.push(i);
}
}
return res;
}