[Leetcode] 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.

 题意:找到字符串中,最大的有效括号数

思路:这题是valid parentheses的扩展,也可以利用栈结构来实现。这里我们用栈存放左括号的下标,遇到左括号,将其下标存入栈中。遇到右括号,若此时栈为空,说明这个不是有效括号对里的,跳过,更新有效括号的起始点;若是栈不为空,则栈顶元素出栈。此时,若栈为空,后面不一定没有接合法的有效括号对,所以,计算当前和有效括号起始点的距离,并更新最大值,如:()();若不为空,用当前位置距离栈顶元素的距离和maxlen中的最大值更新maxlen,如:()(()()。参考了Grandyang的博客。代码如下:

 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) 
 4     {
 5         stack<int> stk;
 6         int start=0,maxLen=0;
 7         for(int i=0;i<s.size();++i)
 8         {
 9             if(s[i]=='(')
10                 stk.push(i);
11             else 
12             {
13                 if(stk.empty())
14                     start=i+1;
15                 else
16                 {
17                     stk.pop();
18                     if(stk.empty())
19                         maxLen=max(maxLen,i-start+1);
20                     else
21                         maxLen=max(maxLen,i-stk.top());
22                 }
23             }
24         }    
25         return maxLen;
26          
27     }
28 };

 

这题还能使用动态规划的方式解:

dp[i]为到i处最长的有效括号,如果s[i]为左括号,则dp[i]为0,因为若字符串是以左括号结束,则不可能为有效的;若是为右括号,有两种情况:

一:其前者s[i-1]为左括号,所以dp[i]=dp[i-2]+2;

二、s[i-1]为右括号且s[i-dp[i-1]-1]为左括号,所以 dp[i] = dp[i-1] + 2 + dp[i-dp[i-1]-2],其中i-dp[i-1]-1对应对应最长括号的起始点

LeetCode OJ代码如下:

 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) 
 4     {
 5         if(s.size()<=1) return 0;
 6         int maxLen=0;
 7         vector<int> dp(s.size(),0);
 8         for(int i=1;i<s.size();++i)
 9         {
10             if(s[i]==')'&&i-dp[i-1]-1>=0&&s[i-dp[i-1]-1]=='(')
11             {
12                 dp[i]=dp[i-1]+2+((i-dp[i-1]-2>=0)?dp[i-dp[i-1]-2]:0);
13                 maxLen=max(dp[i],maxLen);
14             }
15         }
16         return maxLen;
17 
18     }
19  };

 

posted @ 2017-07-16 16:12  王大咩的图书馆  阅读(326)  评论(0编辑  收藏  举报