32. Longest Valid Parentheses

来源:互联网 发布:聚合数据看不懂 编辑:程序博客网 时间:2024/06/06 17:20

题目:

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.

分析:

对于字符串中每一个元素,只有两种取值,'('和')'
所以可分以下情况
  • S[i]等于'('时,因为S[i-1]肯定不能与S[i]组合成有效的一对括号,可以不用考虑
  • S[i]等于')'时,有两种情况
  1. s[i-1]等于'(',则dp[i]=dp[i-2]+2
  2. s[i-1]等于')',则dp[i]=dp[i-1]+2+dp[i-dp[i-1]-2]
因为题意中的Valid指连续的括号才算有效,所以需取最大值

代码:

class Solution {public:    int longestValidParentheses(string s) {         int size=s.size();        if (size<2)  return 0;        vector<int> dp(size,0);        int cmax=0;        for(int i=1;i<size;i++){            if(s[i]==')'){                if(s[i-1]=='(') {                   dp[i]=i-2>=0?(dp[i-2]+2):2;                   cmax=max(cmax,dp[i]);               }            else {                if(i-dp[i-1]-1>=0&&s[i-dp[i-1]-1]=='(') {                   dp[i]=2+dp[i-1]+((i-dp[i-1]-2)>=0?dp[i-dp[i-1]-2]:0);                cmax=max(cmax,dp[i]);                   }                 }            }        }        return cmax;            }};


原创粉丝点击