[leetcode]32. Longest Valid Parentheses

  • 題目描述
    Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
  • 樣例
    Example 1:
    Input: “(()”
    Output: 2
    Explanation: The longest valid parentheses substring is “()”
    Example 2:
    Input: “)()())”
    Output: 4
    Explanation: The longest valid parentheses substring is “()()”
  • 思路
    看了題目標籤顯示是動態規劃(當然就是沒看標籤我也想到了動態規劃,hhhhh)。
    dp[i]表示以i爲結尾的最長的有效括號長度,比如輸入爲")()())",那麼dp[0]=0,dp[1]=0,dp[2]=2,dp[3]=0,dp[4]=4,dp[5]=0。
    轉移方程:
    dp[0] = 0;
    dp[1] = { 2 ,s[0]=’(’ && s[1]=’)’ ; 0, 其他情況 }
    dp[i] = { 0 , s[i] = ‘(’ ; dp[i-2]+2 , s[i]=’)’ && s[i-1]=’(’ ; dp[i-1]+2+dp[i-dp[i-1]-2] , s[i-dp[i-1]-1]=’(’ ; }
    (不怎麼會排版,先湊合着吧。。。)
  • 代碼
class Solution {
public:
   int longestValidParentheses(string s) {
       if(s.length()<=0){
           return 0;
       }
       int dp[s.length()];
       int ans = 0;
       memset(dp, 0, sizeof(dp));
       
       dp[0] = 0;
       if(s[0]=='(' && s[1]==')'){
           dp[1] = 2;
       }
       
       for(int i=2; i<s.length(); i++){
           
           if(s[i] == ')'){//(
               if(s[i-1]=='('){
                   dp[i] = dp[i-2] + 2;
               }else{
                   int n = i - dp[i-1] - 1;
                   if(n>=0){
                       if(s[n]=='('){
                           dp[i] = dp[i-1] + 2;
                           
                           if(n>=1){
                               dp[i] += dp[n-1];
                           }
                           
                       }
                   }else{
                       dp[i] = 0;
                   }
               }
               
               
           }else{//)
               dp[i] = 0;
           }
           
       }
       ans = 0;
       for(int i=0; i<s.length(); i++){
           if(ans<dp[i]){
               ans = dp[i];
           }
           //cout<<dp[i]<<endl;
       }
       return ans;
       
   }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章