32 Longest Valid Parenthese

32 Longest Valid Parenthese




题目链接:32 Longest Valid Parenthese



题意

给出一个由字符’(‘或’)’组成的字符串,求出该字符串中最长合法括号串的长度

解法

求符合要求的最长连续子序列,可用动态规划,L[i]表示以第i个位置结尾的最长合法括号串的长度,则有

L[i]=0,L[i2]+2,L[i1L[i1]]+2+L[i2L[i1]],0,s[i]==(s[i1]==)s[i2]==(s[i2]==)(

用一个变量ans记录最大合法括号串,对于第二三种情况,每次都更新ans的值,使其保持在最大即可,最后返回ans。



代码

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
class Solution {
public:
    int longestValidParentheses(string s) {
        int len = s.length();
        int *L = new int[len + 1];
        memset(L, 0, sizeof(int)*(len + 1));

        int ans = 0;
        for (int i = 2; i <= len; ++i) {
            if (s[i - 1] == '(') {
                L[i] = 0;
            }
            else {
                if (s[i - 2] == '(') {
                    L[i] = L[i - 2] + 2;
                    ans = max(ans, L[i]);
                }
                else {
                    int target = i - 2 - L[i - 1];
                    if (target < 0 || s[target] != '(') {
                        L[i] = 0;
                    }
                    else {
                        L[i] = L[i - 1] + 2 + L[target];
                        ans = max(ans, L[i]);
                    }
                }
            }
        }
        return ans;
    }
};




算法复杂度

算法复杂度为O(n)。n为输入字符串长度。




注意

动态规划数组中每个元素记录的最大合法括号串必须以对应位置结尾,不能只是从开始位置到对应位置形成的区间中的最大合法括号串的长度,因为每个对应位置上的字符必须确定。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值