您当前的位置: 首页 > 

对方正在debug

暂无认证

  • 8浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

最长有效括号(dp/栈/计数)

对方正在debug 发布时间:2020-02-15 20:02:38 ,浏览量:8

题目:https://leetcode-cn.com/problems/longest-valid-parentheses/ 参考了官方orz dp做法: d p [ i ] dp[i] dp[i]表示前 i i i个字符能得到的最大长度

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.length();
        vector dp;
        dp.resize(n+1);
        int ans = 0;
        for(int i = 1;i = 2 ? dp[i-2] : 0) + 2;
                else if(i-1-dp[i-1] >= 0 && s[i-1-dp[i-1]] == '(')
                    dp[i] = dp[i-1] + (i-2-dp[i-1] >= 0 ? dp[i-2-dp[i-1]] : 0) + 2;
                ans = max(ans,dp[i]);
            }
        }
        printf("%d\n",ans);
        return ans;
    }
};

栈做法

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.length();
        stack st;
        int ans = 0;
        st.push(-1);
        for(int i = 0,x;i  
        
       
         r 
        
       
      
        l>r 
       
      
    l>r的情况,如 
     
      
       
       
         ( 
        
       
         ( 
        
       
         ( 
        
       
         ) 
        
       
         ) 
        
       
      
        ((()) 
       
      
    ((()),而这确是从右到左遍历会考虑到的。这两种遍历相辅相成,考虑了所有的情况。

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.length();
        int l = 0,r = 0;
        int ans = 0;
        for(int i = 0;i  r) l = r =0;
        }
        printf("%d\n",ans);
        return ans;
    }
};
关注
打赏
1664895754
查看更多评论
0.0393s