[leetcode] 32. Longest Valid Parentheses 解题报告

本文介绍了一种使用栈和动态规划的方法来解决寻找给定字符串中最长有效括号子串的问题。通过引入栈存储待匹配的左括号位置,并利用动态规划计算合法子串的长度,最终实现O(n)的时间复杂度和O(n)的空间复杂度。

题目链接:https://leetcode.com/problems/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.


思路:引入一个栈和一个辅助数组dp[]。

因为左右括号匹配的性质,对于字符串中的字符我们可以做两种操作:

1. 如果是‘(’,则将其位置入栈,代表这个位置有一个需要匹配的左括号。

2. 如果是‘)’,则查找栈:

1)如果此时栈为空,则说明当前段字符串是不合法的。

2)如果此时栈不为空,则说明当前的‘)’可以被匹配。则将从当前‘)’到栈中‘(’位置区间是合法的字符串,则当前合法子串的长度则为

dp[i+1] = (i - j + 1) + dp[j];

即当前匹配的括号的区间长度加上‘(’之前合法子串的长度。

时间复杂度为O(n),空间复杂度为O(n)。

代码如下:

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

或者不借助栈, 直接查看和当前右括号匹配的左括号之前的匹配长度和这两个匹配之间的长度.

代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        int len = s.size(), ans = 0;
        vector<int> dp(len+1, 0);
        for(int i = 2; i <= len; i++)
        {
            if(s[i-1]=='(') continue;
            if(i-dp[i-1]-2 >= 0 && s[i-dp[i-1]-2]=='(') 
                dp[i] = dp[i-2-dp[i-1]] + dp[i-1]+2;
            ans = max(ans, dp[i]);
        }
        return ans;
    }
};

或者不用dp, 只用stack

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值