32. Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
// Dynamic programming
int longestValidParentheses(string s) { // time: O(n); space: O(n)
int n = s.length(), res = 0;
if (n <= 1) return res;
vector<int> longest(n, 0);
for (int i = 1; i < n; ++i) {
if (s[i] == '(') continue;
if (s[i] == ')') {
if (s[i - 1] == ')') {
if (i - 1 - longest[i - 1] >= 0 && s[i - 1 - longest[i - 1]] == '(') {
longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2) >= 0? longest[i - longest[i - 1] - 2] : 0);
}
} else { // s[i - 1] == '('
longest[i] = (i >= 2 ? longest[i - 2] : 0) + 2;
}
}
res = max(res, longest[i]);
}
return res;
}
// Stack
int longestValidParentheses(string s) { // time: O(n); space: O(n)
int n = s.length(), res = 0;
if (n <= 1) return res;
int start = 0; // the starting position of valid parentheses
stack<int> st;
for (int i = 0; i < n; ++i) {
if (s[i] == '(') st.push(i);
else {
if (st.empty()) start = i + 1;
else {
st.pop();
res = max(res, (st.empty() ? i - start + 1: i - st.top()));
}
}
}
return res;
}
Last updated
Was this helpful?