Hard
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”.
Example 2:
Input: s = “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”.
Example 3:
Input: s = “”
Output: 0
Constraints:
0 <= s.length <= 3 * 104
s[i]
is '('
, or ')'
.To solve the “Longest Valid Parentheses” problem in Java with a Solution
class, we can follow these steps:
Solution
class.longestValidParentheses
that takes a string s
as input and returns an integer representing the length of the longest valid parentheses substring.maxLen
to store the maximum length of valid parentheses found so far.-1
onto the stack to mark the starting point of a potential valid substring.'('
, push its index onto the stack.')'
:
maxLen
with the maximum of the current maxLen
and i - stack.peek()
, where i
is the current index and stack.peek()
is the index at the top of the stack.maxLen
.Here’s the implementation:
import java.util.Stack;
public class Solution {
public int longestValidParentheses(String s) {
int maxLen = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1); // Mark the starting point of a potential valid substring
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else { // c == ')'
stack.pop();
if (stack.isEmpty()) {
stack.push(i); // Mark the starting point of the next potential valid substring
} else {
maxLen = Math.max(maxLen, i - stack.peek());
}
}
}
return maxLen;
}
}
This implementation provides a solution to the “Longest Valid Parentheses” problem in Java. It finds the length of the longest valid parentheses substring in the given string s
.