Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
My Code Using Stack
The workflow of the solution is as below.
- Scan the string from beginning to end.
- If current character is '(', push its index to the stack. If current character is ')' and the character at the index of the top of stack is '(', we just find a matching pair so pop from the stack. Otherwise, we push the index of ')' to the stack.
- After the scan is done, the stack will only contain the indices of characters which cannot be matched. Then let's use the opposite side - substring between adjacent indices should be valid parentheses.
- If the stack is empty, the whole input string is valid. Otherwise, we can scan the stack to get longest valid substring as described in step 3.
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.length();
int res = 0;
stack<int> stk;
for (int i = 0; i < len; i++)
{
if (s[i] == '(')
stk.push(i);
else
{
if (stk.empty())
stk.push(i);
else
{
if (s[stk.top()] == '(')
{
stk.pop();
if (stk.empty())
res = i + 1;
else
res = max(res, i - stk.top());
}
else
stk.push(i);
}
}
}
return res;
}
};
Runtime: 12 ms
My DP Code
The DP idea is :
If s[i] is '(', set longest[i] to 0,because any string end with '(' cannot be a valid one.
Else if s[i] is ')'
If s[i-1] is '(', longest[i] = longest[i-2] + 2
Else if s[i-1] is ')' and s[i-longest[i-1]-1] == '(', longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]
For example, input "()(())", at i = 5, longest array is [0,2,0,0,2,0], longest[5] = longest[4] + 2 + longest[1] = 6.
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.length();
int res = 0;
vector<int> longest(len, 0);
for (int i = 1; i < len; i++)
{
if (s[i] == ')')
{
if (s[i-1] == '(')
{
if (i == 2)
longest[i] = 2;
else
longest[i] = longest[i-2] + 2;
res = max(res, longest[i]);
}
else
{
if (i - longest[i-1] - 1 >= 0 && s[i - longest[i-1] - 1] == '(')
{
if (i - longest[i-1] - 2 >= 0)
longest[i] = longest[i-1] + 2 + longest[i - longest[i-1] - 2];
else
longest[i] = longest[i-1] + 2;
}
res = max(res, longest[i]);
}
}
}
return res;
}
};
Runtime: 8 ms