
Problem
Solution
Submissions
Longest Valid Parentheses
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find the length of the longest valid parentheses substring. A valid parentheses substring is a string of parentheses where every opening parenthesis '(' has a matching closing parenthesis ')' and they are correctly nested.
Example 1
- Input: s = "(()"
- Output: 2
- Explanation: The last two characters "()" form a valid parentheses pair. The length of this valid substring is 2. Therefore, the longest valid parentheses substring has length 2.
Example 2
- Input: s = ")()())"
- Output: 4
- Explanation: The first character ")" has no matching opening parenthesis, so it's invalid. The next four characters "()()" form a valid parentheses substring. The length of this valid substring is 4. Therefore, the longest valid parentheses substring has length 4.
Constraints
- 0 <= s.length <= 3 * 10^4
- s consists of only '(' and ')' characters
- Time Complexity: O(n) where n is the length of the string
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a stack data structure to keep track of the indices of opening parentheses
- Push -1 onto the stack initially as a base marker
- Iterate through the string, if the current character is '(', push its index onto the stack
- If the current character is ')', pop the top element from the stack
- If the stack becomes empty, push the current index as a new base marker
- If the stack is not empty, calculate the length of the current valid substring (current index - index at the top of the stack)
- Update the maximum length found so far