Longest Valid Parentheses
Given a string containing just the characters '(' and ')', return 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
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
// Push -1 as a base for the first valid substring calculation
stack.push(-1);
int maxlength = 0; // Stores the maximum length of valid parentheses
// Iterate through the characters of the string
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(') {
// Push the index of '(' onto the stack
stack.push(i);
} else {
// Pop the last index as we found a closing ')'
stack.pop();
if (stack.isEmpty()) {
// If stack is empty after popping, push current index as new base
stack.push(i);
} else {
// Calculate the length of the current valid substring
int length = i - stack.peek();
maxlength = Math.max(maxlength, length);
}
}
}
return maxlength;
}
}
Comments
Post a Comment