Leetcode 32. 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.



解决方法:

这道题既可以用stack的方法来解,也可以使用DP的方法来解。

当使用stack,首先将-1压栈,然后遇到‘(’入栈;遇到')'出栈,然后计算当前的有效长度,如果stack为空,表明')'有多余的,将当前位置压栈做为后面字符的有效起始位置。

当使用DP时,比较难的是得到推导公式。当是'(',不需要计算。当是')'时,首先判断前一个字符是不是'(',如果是,很容易知道有效长度就是dp[i-2] + 2; 当前一个也是')'时,有效的字符串可以分成三部分:有效字符串 +'(' + 前一个')'组成的有效字符串 + ')',从而推导公式是dp[i] = dp[i-dp[i-1] -2] + 1 + dp[i-1] + 1。


代码:
int longestValidParentheses(string s) {
        int n = s.size(), res = 0;
        vector<int> dp(n, 0);
        for(int i = 1; i < n; i++){
            if (s[i] == '(')
                continue;
            
            if (s[i-1] == '('){
                dp[i] = ((i >= 2) ? dp[i-2] : 0) + 2;
            }else if ( (i-dp[i-1]) > 0 && s[i-dp[i-1] - 1]=='('  ){
                dp[i] = dp[i-1] + dp[i-dp[i-1] - 2] + 2;
            }
            res = max(res, dp[i]);
        }
        
        return res;
    }
    
    int longestValidParentheses1(string s) {
        stack<int> st;
        st.push(-1);
        int res = 0;
        for(int i = 0; i < s.size(); i++){
            if (s[i] == '('){
                st.push(i);
            }else{
                st.pop();
                if (st.empty()){
                    st.push(i);
                }else{
                    res = max(res, i - st.top());
                }
            }
        }
        
        return res;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值