AlgoMaster Logo

Longest Valid Parentheses

s=(()
1public int longestValidParentheses(String s) {
2    Stack<Integer> stack = new Stack<>();
3    stack.push(-1);
4    int maxLength = 0;
5
6    for (int i = 0; i < s.length(); i++) {
7        if (s.charAt(i) == '(') {
8            stack.push(i);
9        } else {
10            stack.pop();
11            if (stack.isEmpty()) {
12                stack.push(i);
13            } else {
14                maxLength = Math.max(maxLength, i - stack.peek());
15            }
16        }
17    }
18
19    return maxLength;
20}
0 / 10
(()stack