
Problem
Solution
Submissions
Longest Valid Parentheses
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the length of the longest valid (well-formed) parentheses substring. Given a string containing just the characters '(' and ')', find the length of the longest valid parentheses substring.
Example 1
- Input: s = "(()"
- Output: 2
- Explanation:
- Step 1: The longest valid parentheses substring is "()".
- Step 2: This substring has length 2.
- Step 3: Therefore, the answer is 2.
Example 2
- Input: s = ")()())"
- Output: 4
- Explanation:
- Step 1: The longest valid parentheses substring is "()()".
- Step 2: This substring has length 4.
- Step 3: Therefore, the answer is 4.
Constraints
- 0 ≤ strlen(s) ≤ 3 * 10^4
- s[i] is '(' or ')'
- Time Complexity: O(n)
- 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 to keep track of indices of characters.
- Push -1 initially to handle base case.
- For each '(', push its index onto the stack.
- For each ')', pop from stack and calculate current valid length.
- Keep track of the maximum length found so far.
- If stack becomes empty after popping, push current index.