32. Longest Valid Parentheses
Explanation:
To solve this problem, we can use a stack to keep track of the indices of the opening parentheses. We iterate through the input string and whenever we encounter an opening parenthesis, we push its index onto the stack. When we encounter a closing parenthesis, we check if the stack is empty. If it is empty, we update the starting index for the next valid substring. If the stack is not empty, we pop the top index from the stack and calculate the length of the current valid substring.
We also need to handle cases where there are unmatched parentheses. To do this, we initialize the starting index as -1 and update it whenever we encounter a closing parenthesis with an empty stack.
Finally, the length of the longest valid substring will be the maximum difference between the current index and the starting index.
Time Complexity: O(n) - where n is the length of the input string. Space Complexity: O(n) - for the stack to store indices.
:
class Solution {
public int longestValidParentheses(String s) {
int maxLen = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.