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.

思路1:stack
我们还是借助栈来求解,需要定义个start变量来记录合法括号串的起始位置,我们遍历字符串,如果遇到左括号,则将当前下标压入栈,如果遇到右括号,如果当前栈为空,则将下一个坐标位置记录到start,如果栈不为空,则将栈顶元素取出,此时若栈为空,则更新结果和i - start + 1中的较大值,否则更新结果和i - 栈顶元素中的较大值,代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        int res = 0, start = 0;
        stack<int> m;
        for(int i = 0; i < s.size(); ++i) {
            if(s[i] == '(') 
                m.push(i);
            else {
                if(m.empty()) 
                    start = i+1;
                else {
                    m.pop();
                    if(m.empty())
                        res = max(res, i - start + 1);
                    else
                        res = max(res, i - m.top());
                }
            }
        }
        return res;
    }
};

思路2:DP
求极值问题一般想到DP或Greedy,显然Greedy在这里不太适用,只有用DP了。

  1. 状态:
    DP[i]:以s[i]为结尾的longest valid parentheses substring的长度。

  2. 通项公式:
    s[i] = ‘(‘:
    DP[i] = 0

s[i] = ‘)’:找i前一个字符的最长括号串DP[i]的前一个字符j = i-1-DP[i-1]
DP[i] = DP[i-1] + 2 + DP[j-1],如果j >=0,且s[j] = ‘(’
DP[i] = 0,如果j<0,或s[j] = ‘)’

  1. 计算方向
    显然自左向右,且DP[0] = 0
class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size(), res = 0;
        vector<int> dp(n, 0);
        for(int i = 1; i < n; ++i) {
            int j = i-1-dp[i-1];
            if(s[i] == '(' || j < 0 || s[j] == ')')
                dp[i] = 0;
            else {
                dp[i] = dp[i-1] + dp[j-1] + 2;
                res = max(res, dp[i]);
            }

        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值