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.
Subscribe to see which companies asked this question
class Solution {
public:
int longestValidParentheses(string s) {
/*
stack<int> stk;
stk.push(-1);
int maxL=0;
for(int i=0;i<s.size();i++)
{
int t=stk.top();
if(t!=-1&&s[i]==')'&&s[t]=='(')
{
stk.pop();
maxL=max(maxL,i-stk.top());
}
else
stk.push(i);
}
return maxL;
*/
stack<int> auxStack;
int startIdx = -1;
int curLen = 0;
int maxLen = 0;
for (int i=0; i<s.size(); i++)
{
if (s[i] == '(')
{
auxStack.push(i);
}
else
{
if (auxStack.size() > 0)
{
auxStack.pop();
if (auxStack.size() == 0)
{
curLen = i-startIdx;
}
else
{
curLen = i-auxStack.top();
}
maxLen = max(curLen, maxLen);
}
else
{
startIdx = i;
}
}
}
return maxLen;
}
};
参照网址:
https://leetcode.com/discuss/8092/my-dp-o-n-solution-without-using-stack
My solution uses DP. The main idea is as follows: I construct a array longest[], for any longest[i], it stores the longest length of valid parentheses which is end at i.
And 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.
int longestValidParentheses(string s) {
if(s.length() <= 1) return 0;
int curMax = 0;
vector<int> longest(s.size(),0);
for(int i=1; i < s.length(); i++){
if(s[i] == ')'){
if(s[i-1] == '('){
longest[i] = (i-2) >= 0 ? (longest[i-2] + 2) : 2;
curMax = max(longest[i],curMax);
}
else{ // if s[i-1] == ')', combine the previous length.
if(i-longest[i-1]-1 >= 0 && s[i-longest[i-1]-1] == '('){
longest[i] = longest[i-1] + 2 + ((i-longest[i-1]-2 >= 0)?longest[i-longest[i-1]-2]:0);
curMax = max(longest[i],curMax);
}
}
}
//else if s[i] == '(', skip it, because longest[i] must be 0
}
return curMax;
}
Updated: thanks to Philip0116, I have a more concise solution(though this is not as readable as the above one, but concise):
int longestValidParentheses(string s) {
if(s.length() <= 1) return 0;
int curMax = 0;
vector<int> longest(s.size(),0);
for(int i=1; i < s.length(); i++){
if(s[i] == ')' && i-longest[i-1]-1 >= 0 && s[i-longest[i-1]-1] == '('){
longest[i] = longest[i-1] + 2 + ((i-longest[i-1]-2 >= 0)?longest[i-longest[i-1]-2]:0);
curMax = max(longest[i],curMax);
}
}
return curMax;
}

本文介绍了一种使用栈和动态规划方法解决寻找字符串中最长有效括号子串的问题。通过两种不同方法的代码实现,详细展示了如何找到给定字符串中包含字符 '(' 和 ')' 的最长有效子串长度。
276

被折叠的 条评论
为什么被折叠?



