[C++] LeetCode 32. 最长有效括号

题目

给一个只包含'('')'的字符串,找出最长的有效(正确关闭)括号子串的长度。
对于 "(()",最长有效括号子串为 "()",它的长度是 2
另一个例子 ")()())",最长有效括号子串为 "()()",它的长度是4

方法一

这道题可以考虑用栈来实现,这样一次遍历就可以OK了。假定(用数字-2表示,)用数字-1表示,正数表示现阶段可以组成封闭括号的长度。
如果遇到(直接入栈
如果遇到)考虑如下几种情况:
1、栈为空,此时直接continue即可
2、栈顶为(,则可以配对,栈弹出栈顶元素,如果此时栈顶为正数,则弹出正数加2重新入栈,否则直接压入2
3、栈顶为正数,则弹出栈顶元并记录,此时针对栈顶元考虑步骤12的情况。

代码如下

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        int res=0;
        for(int i=0;i<s.size();i++){
            if(s[i]=='('){
                st.push(-2);
                continue;
            }
            if(st.empty()) continue;
            if(st.top()==-2){
                st.pop();
                if(st.empty()||st.top()<0) st.push(2);
                else{
                    int tmp=st.top()+2;
                    st.pop();
                    st.push(tmp);
                }
                res=max(res,st.top());
                continue;
            }
            if(st.top()>0){
                int tmp=st.top();
                st.pop();
                if(st.empty()) continue;
                else{
                    tmp+=2;
                    st.pop();
                    while(!st.empty()&&st.top()>0){
                        tmp+=st.top();
                        st.pop();
                    }
                    st.push(tmp);
                    res=max(res,st.top());
                }
            }

        }
        return res;
    }
};

方法二

这题可以用动态规划求解,开一个数组vector<int> count表示以i位置结尾的最长有效括号子串的长度。如果s[i]==')'j=i-1-count[i-1];

  • s[i-1]=='(',则j=i-1,此时考虑count[i]=2+count[i-2]=2+count[j-1]
  • s[i-1]==')',则j=i-1-count[i-1],此时如果s[j]=='(',则count[i]=2+count[i-1]+count[j-1](例如s=()(())
  • 综合上述两种情况,可以写成count[i]=2+count[i-1]+count[j-1]

代码

class Solution {
public:
    int longestValidParentheses(string s) {
        int n=s.size(),res=0;
        vector<int> count(n,0);
        for(int i=1;i<n;i++){
            if(s[i]=='(') continue;
            int j=i-1-count[i-1];
            if(s[j]=='(')
                count[i]=2+count[i-1]+(j>0?count[j-1]:0);
            res=max(res,count[i]);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值