Back to DSA
Longest Valid Parentheses
hardA string consisting exclusively of opening '(' and closing ')' parentheses is given. Determine the length of the longest contiguous substring that forms a correctly matched sequence of parentheses.
Examples
Example 1:
Input:
s = "()(()"Output:
2Explanation: The longest well-matched segment is '()' with length 2.
Example 2:
Input:
s = "(())()"Output:
6Explanation: The entire string is validly matched, so the answer is 6.
Hints
import java.util.*;
class Solution {
public int longestValidParentheses(String s) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(-1);
int maxLen = 0;
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 {
maxLen = Math.max(maxLen, i - stack.peek());
}
}
}
return maxLen;
}
}Time complexity
O(n)Space complexity
O(1)