栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode——32. Longest Valid Parentheses(C++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode——32. Longest Valid Parentheses(C++)

LeetCode——32. Longest Valid Parentheses(C++)
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”.

Example 2:
Input: s = “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”.

Example 3:
Input: s = “”
Output: 0

Constraints:
0 <= s.length <= 3 * 104
s[i] is ‘(’, or ‘)’.

解题思路:
动态规划,dp[i]存储以i为终点时,此处往前有几个连续对子,
从0开始遍历,所有‘(’的对应的dp数组值为0,遇到‘)’则考察其往前可配对的情况,前一个为‘(’则其dp值为前前一个的dp值+2(相关边界情况见代码),前一个为‘)’则考察此‘)’的dp值,非零则进行进一步计算,为零则当前dp也为零;
代码:

class Solution {
public:
    int longestValidParentheses(string s) {
        int siz=s.size();
        vectordp;
        dp.resize(siz,0);
        int maxsiz=0;    //记录最大的配对数
        for(int i=0;i
            if(i&&s[i]==')')
            {
                if(s[i-1]=='(')
                {
                    if(i>2)dp[i]=2+dp[i-2];
                    else dp[i]=2;
                    if(maxsiz
                    if(i-1-dp[i-1]>=0&&s[i-1-dp[i-1]]=='(')
                    {
                        if(i-1-dp[i-1]==0)
                        dp[i]=dp[i-1]+2;
                        else
                          dp[i]=dp[i-1]+2+dp[i-1-dp[i-1]-1];  
                        if(maxsiz 

submission:

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015171.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号