LeetCode Longest Valid Parentheses的O(N)解法

/************************************************************************
*
* 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.
*
*
************************************************************************/
用栈去解:压入栈的是索引,这样便于计算长度

  1. 如果此时的元素为(直接压入栈,因为前面的元素没有和他能配对的。

  2. 如果此时元素为),分两种情况:
    a. 栈为空,则直接将其压入栈中。
    b. 栈不空,看栈顶元素是否是(,若是,将其弹出,因为他们能组成一对,若不是,则将其压入栈中。

我们在第二步符合弹出元素是,计算此时的最大长度maxLen=max(maxLen,i-(st.empty()? -1:st.top()));
其中,分为栈为空和不空的两种情况:
综上所述,代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size(),maxLen=0;
        if (n<2) return 0;
        stack<int> st;
        for (int i=0;i<n;i++) {
            if (s[i]=='(') st.push(i);
            else {
                if (st.empty()) st.push(i);
                else {
                    if (s[st.top()]=='(') {
                        st.pop();
                        maxLen=max(maxLen,i-(st.empty()? -1:st.top()));
                    }
                    else st.push(i);
                }
            }
        }
        return maxLen;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值