LeetCode32. Longest Valid Parentheses——动态规划

文章目录

一、题目

Given a string containing just the characters ‘(’ and ‘)’, return 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 ‘)’.

二、题解

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

相关推荐

  1. LeetCode32. Longest Valid Parentheses——动态规划

    2024-02-10 10:50:02       45 阅读
  2. 动态规划 Leetcode 322 零钱兑换

    2024-02-10 10:50:02       197 阅读
  3. 动态规划 Leetcode 392 判断子序列

    2024-02-10 10:50:02       31 阅读
  4. 动态规划Leetcode 322. 零钱兑换【中等】

    2024-02-10 10:50:02       25 阅读
  5. 动态规划Leetcode 32. 最长有效括号【困难】

    2024-02-10 10:50:02       34 阅读
  6. LeetCode——动态规划

    2024-02-10 10:50:02       42 阅读
  7. [LeetCode]-动态规划-4

    2024-02-10 10:50:02       47 阅读
  8. leetcode动态规划专题

    2024-02-10 10:50:02       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-10 10:50:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-10 10:50:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-10 10:50:02       87 阅读
  4. Python语言-面向对象

    2024-02-10 10:50:02       96 阅读

热门阅读

  1. django中实现登录

    2024-02-10 10:50:02       54 阅读
  2. Linux学习

    2024-02-10 10:50:02       40 阅读
  3. 配置ARM交叉编译工具的通用步骤

    2024-02-10 10:50:02       41 阅读
  4. B站弹幕分析系统

    2024-02-10 10:50:02       46 阅读
  5. 蓝桥杯:大写

    2024-02-10 10:50:02       41 阅读
  6. H5/CSS 笔试面试考题(71-80)

    2024-02-10 10:50:02       44 阅读
  7. vue3 源码解析之Reactive实现的原理

    2024-02-10 10:50:02       50 阅读
  8. 第四章 未知的起源

    2024-02-10 10:50:02       41 阅读
  9. Element-Ui el-date-picker日期传值异常问题解决办法

    2024-02-10 10:50:02       47 阅读
  10. postgresql的扩展:pg_net

    2024-02-10 10:50:02       57 阅读
  11. 236. 二叉树的最近公共祖先

    2024-02-10 10:50:02       48 阅读