您的位置:首页 > 其它

leetcode Longest Valid Parentheses

2013-11-27 13:59 204 查看
这个星期没有做题,跑出去玩了一圈。投个实习感觉被鄙视了,回来继续学习算了。

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.
这个就是求最长的匹配连续子串,题目也比较好理解。分析下题目,其实就是所有的‘)‘ 看这个往前能匹配多长。所有的')'都跑一遍就能找出最长的。思想类似dp,开始的时候我用了二维bool空间记录i,j匹配程度,好像会超时。后来换成一维int空间,记录i能匹配到前面的某个下标。
我的思路:使用dp[i]==j,表示i到某个j结点能够匹配。初始dp[i]==i;

1)如果遇到某个 s[i]==')',去找他的匹配'(',往前找第一个(离i最近)没有匹配的s[j]=='(',如果找到就更新dp[i]==j,进入2;否则不能匹配。

2)当找到s[j]=='('时,同时dp[j-1]能够往前匹配,就更新dp[i]。

往前找匹配的过程开始用while写,后来想想不用循环,循环也只会执行一次。因为前面已经更新了。代码也不长,应该还算简单点。这个时间复杂度应该是O(N)的,所以应该还算快的。

class Solution {
public:
int longestValidParentheses(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int mm=0;
int n=s.size();
int dp
;
for(int i=0;i<n;i++)
dp[i]=i;
for(int i=1;i<n;i++)
{
if(s[i]=='(')
continue;
int j=i-1;
if(j>=0 &&j!=dp[j])
{
j=dp[j]-1;
}
if(s[j]=='(')
{
dp[i]=j;
j--;
if(j>=0&&j!=dp[j])
{
j=dp[j]-1;
}
if(j!=dp[i]-1)
dp[i]=j+1;
}
if(i!=dp[i]&&i-dp[i]+1>mm)
mm=i-dp[i]+1;
}
return mm;
}
};
这是大概写出了自己的思考过程,如果有不对的地方请指正谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息