[Link] https://leetcode.com/problems/longest-valid-parentheses/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack();
char[] chars = s.toCharArray();
int max = 0;
stack.push(-1);
for(int i = 0, len = chars.length; i < len; i++) {
if(chars[i] == '(') stack.push(i);
else {
stack.pop();
if(!stack.isEmpty()) max = Math.max(max, i - stack.peek());
else stack.push(i);
}
}
return max;
}
}