class Solution {
public int longestValidParentheses(String s) {
//()) 2() 最开始放的-1就是为了应对这种情况,1-(-1)=2
//(() 2()
//)()())() 4()()
//((()
//)))()
int count = 0;
int len = s.length();
Deque<Integer> stack = new LinkedList<Integer>();
stack.push(-1);
for (int i = 0; i < len; i++) {
if (s.charAt(i) == '(')
stack.push(i);
else { //')'
stack.pop();
if (stack.isEmpty()) {//栈空把")'放进去
stack.push(i);
} else {//栈不空 -1 () :1-(-1)=2
count = Math.max(count, i - stack.peek());
}
}
}
return count;
}
}
栈中只保存左括号的下标,每遍历到右括号就出栈,比较当前最大合法长度。