您的位置:首页 > 其它

32. Longest Valid Parentheses

2015-07-13 20:41 441 查看
此道题目有两种解法,一种是使用stack,一种是使用DP。先介绍stack解法。

stack解法

stack里面一直放的是"还没配好对的那些可怜的括号的index"
是'(‘的时候push
是')'的时候,说明可能配对成功;看stack top是不是左括号,不是的话,push当前右括号
是的话,pop那个配对的左括号,然后update res:i和top的(最后一个没配对的)index相减,就是i属于的这一段的当前最长。如果一pop就整个栈空了,说明前面全配好对了,那res就是最大=i+1代码如下:

class Solution {
public:
int longestValidParentheses(string s) {
int res = 0, len = (int)s.length();
stack<int> sta;
for (int i=0; i<len; i++) {
if (s[i] == ')' && !sta.empty() && s[sta.top()] == '(') { // 配对的条件
sta.pop();
if (sta.empty()) // pop后sta空了
res = i + 1;
else
res = max(res, i - sta.top()); // update res
} else {
sta.push(i);
}
}
return res;
}
};


DP解法

括号题也不是只用stack才能做,这道题目是算最长有效括号长度,算是求极值。求极值,一维dp在这里很合适。

d[i]:以i开始的最长valid parentheses有多长。
d[i] =

if (str[i] == ‘)’),以右括号开头必定invalid,d[i] = 0
if (str[i] == ‘(‘),以左括号开头

我们想看相应的位置有没有右括号。因为d[i + 1]代表的括号sequence肯定是左括号开头右括号结尾或者其长度为0,所以我们想catch((…))这种情况。j = i + 1 + d[i + 1],正好就是str[i]后面越过d[i+1]所代表的括号sequence的下一个位置,若是右括号,d[i]
= 2 + d[i + 1]
除此之外,还有d[i]右括号结束后,与后面的括号序列连接起来的情况,如((..))()()()。所以d[i]还要再加上j后面那一段的d[j + 1]。

代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
int len = (int)s.length(), res = 0;
if (len == 0)
return 0;
int* d = new int[len](); // 注意,这里是动态数组的值初始化,只能用()这唯一的方式,(0), (-1),或者new int[len]都是错误的。
// d[i] means substring starts with i has max valid lenth of d[i]
for (int i=len-2; i >= 0; i--) {
if (s[i] == '(') {
int j = (i + 1) + d[i + 1];
if (j<len && s[j] == ')') {
d[i] = d[i + 1] + 2; // (()())的外包情况
if (j + 1 < len)
d[i] += d[j + 1]; // (())的后面还有的情况
}
}
res = max(res, d[i]);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: