8.1 Longest Valid Parentheses
8.1.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 32
- Difficulty: Hard
- URL: https://leetcode.com/problems/lc-longest-valid-parentheses/
- Tags:
- Techniques: Dynamic Programming, Stack
8.1.2 Description
Given a string containing only '(' and ')', return the length of the longest well-formed parentheses substring.
8.1.5 Solution - Stack
8.1.5.1 Walkthrough
Maintain a stack of indices. Push -1 as a sentinel. For each character:
- When '(', push its index.
- When ')', pop the stack. If it becomes empty, push the current index (new base). Otherwise update the answer with i - stack.peek().
8.1.5.3 Implementation Steps
- Initialize stack with
-1andmaxLen = 0. - For each index
i:- If
s[i] == '(', pushi. - Else pop; if stack empty push
i, elsemaxLen = max(maxLen, i - stack.peek()).
- If
- Return
maxLen.
8.1.5.4 Code - Java
public int longestValidParentheses(String s) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(-1);
int longest = 0;
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 {
longest = Math.max(longest, i - stack.peek());
}
}
}
return longest;
}