[LeetCode] 032. Longest Valid Parentheses (Hard) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


032. Longest Valid Parentheses (Hard)

链接

题目:https://oj.leetcode.com/problems/longest-valid-parentheses/
代码(github):https://github.com/illuz/leetcode

题意

问一个字符串里最长的合法括号串的长度。

分析

  1. (C++)用栈来做,如果匹配就出栈,然后长度就是 cur - stack_top_pos 也就是 - 匹配的前一个位置。 O(n) time, O(n) space。
  2. (C++)栈消耗空间太多了,其实可以维护 () 匹配的长度,不过可能出现 ())) ((() 的情况,所以要前后各扫一遍。O(n) time, O(1) space。
  3. 用较复杂的 DP 来做,不过空间可没解法 2 那么优了。刚看到我很久前的一个解法,用太多空间了Orz。现在来看还是 1、2 的做法好。

代码

解法 1:(C++)

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> lefts;
        int max_len = 0, match_pos = -1;    // position of first
                                            // matching '(' - 1

        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(')
                lefts.push(i);
            else {
                if (lefts.empty())  // no matching left
                    match_pos = i;
                else {              // match a left
                    lefts.pop();
                    if (lefts.empty())
                        max_len = max(max_len, i - match_pos);
                    else
                        max_len = max(max_len, i - lefts.top());
                }
            }
        }

        return max_len;
    }
};


解法 2:(C++)

class Solution {
public:
    int longestValidParentheses(string s) {
        int max_len = 0, depth = 0, start = -1;

        // solve ((()
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(')
                ++depth;
            else {
                --depth;
                if (depth == 0)
                    max_len = max(max_len, i - start);
                else if (depth < 0) {
                    start = i;
                    depth = 0;
                }
            }
        }

        // solve ()))
        depth = 0;
        start = s.size();
        for (int i = s.size(); i >= 0; --i) {
            if (s[i] == ')')
                ++depth;
            else {
                --depth;
                if (depth == 0)
                    max_len = max(max_len, start - i);
                else if (depth < 0) {
                    start = i;
                    depth = 0;
                }
            }
        }

        return max_len;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值