【C++】 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.

Subscribe to see which companies asked this question.

思路解析:

这题是括号配对问题,可以采用栈,如果是左括号则入栈,如果是右括号且栈顶为左括号,则栈顶元素出栈,否则右括号入栈。
但是该题要求最长的有效括号,需要记录出栈的元素的数量。
故采用了pair类型,左括号对应-1,右括号对应1,first记录括号类型,second记录在此之前出栈的元素的数量。
1、如果元素出栈则将已出栈数量增加到栈顶元素second
2、如果元素出栈且栈为空,则新生成一个pair类型,first和sencond均记录已出栈元素(大于1)。
2、如果元素不配对,则second为0,压入栈

代码:

class Solution {
public:
    int longestValidParentheses(string s) {
        int n=s.size();
        if(s.size()<2)return 0;
        pair<int,int> p;
        stack<pair<int,int>> st;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='(')
            {
                p.first=-1;
                p.second=0;
                st.push(p);
            }
            else
            {
                if(!st.empty()&&st.top().first==-1)
                {
                    int temp=st.top().second;
                    st.pop();
                    if(st.empty())
                    {
                        p.first=temp+2;
                        p.second=p.first;
                        st.push(p);
                    }
                    else
                    {
                        st.top().second+=temp+2;
                    }
                }
                else
                {
                    p.first=1;
                    p.second=0;
                    st.push(p);
                }
            }
        }
        int max=0;
        while(st.size()>1)
        {
            int num=st.top().second;
            int first=st.top().first;
            st.pop();
            if(first>1)
                st.top().second+=num;
            else
                max=max>num?max:num;
        }
        return max>st.top().second?max:st.top().second;
    }
};

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值