您的位置:首页 > 其它

32. Longest Valid Parentheses (Stack; DP)

2015-10-04 10:05 477 查看
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.

法I:把所有invalid的括号位置都标记出来,比较invalid之间的长度哪段最长

class Solution {
public:
int longestValidParentheses(string s) {
vector<int> invalidPos;
invalidPos.push_back(-1);
invalidPos.push_back(s.length());
stack<int> lParenPos;
int len = 0, ret = 0;

for(int i = 0; i < s.length(); i++){
if(s[i]=='('){
lParenPos.push(i);
}
else{ //right parenthese
if(lParenPos.empty()){
invalidPos.push_back(i);
}
else{
lParenPos.pop();
}
}
}

while(!lParenPos.empty()){
invalidPos.push_back(lParenPos.top());
lParenPos.pop();
}

sort(invalidPos.begin(), invalidPos.end());
for(int i = 1; i < invalidPos.size(); i++){
len = invalidPos[i]-invalidPos[i-1]-1;
if(len > ret) ret = len;
}

return ret;
}
};


法II:动态规划

class Solution {
public:
int longestValidParentheses(string s) {
if(s.empty()) return 0;
stack<int> leftStack;
int ret = 0;
int currentMax = 0;
int leftPos;
vector<int> dp(s.length()+1,0); //currentMax无法检测到连续valid的情况,eg: ()(), 所以需要动态规划记录i位置之前连续多少个valid。

for(int i = 0; i <s.length(); i++){
if(s[i]==')'){
if(leftStack.empty()){
currentMax = 0;
}
else
{
leftPos = leftStack.top();
leftStack.pop();
currentMax = i-leftPos+1 + dp[leftPos];
dp[i+1] = currentMax;
ret = max(ret,currentMax);
}
}
else{
leftStack.push(i); //push the index of '('
}
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: