Fancy DSA Fancy DSA
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)

Jonsam NG

想的更多,也要想的更远
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)
  • 开始上手
  • Plan 计划
  • Roadmap 路线
  • 算法简介
  • Sort 排序

  • Search 搜索

  • Recursive 递归

  • Graph 图

  • Tree 树

  • Math 数学

  • Hash 哈希

  • String 字符串

  • BitManipulation 位操纵

  • Backtracking 回溯

  • DynamicProgramming 动态规划

    • ClimbingStairs [爬楼梯]
    • CoinChange [钱币兑换]
    • EditDistance [编辑距离]
    • FibonacciNumber [斐波那契数]
    • FindMonthCalendar [月历]
    • KadaneAlgo [最大连续子数组和之Kadane算法]
    • LevenshteinDistance [莱文斯坦距离]
    • LongestCommonSubsequence [最长公共子序列]
    • LongestIncreasingSubsequence [最长递增子序列]
    • LongestPalindromicSubsequence [最长回文子序列]
    • LongestValidParentheses [最长合法括号]
      • 介绍
      • 实现
      • 参考
    • MaxNonAdjacentSum [最大非连接子集和]
    • MaxProductOfThree [最大三数积]
    • MinimumCostPath [最小代价路径]
    • NumberOfSubsetEqualToGivenSum [等和子集]
    • RodCutting [棒材切割问题]
    • Shuf [随机样本]
    • SieveOfEratosthenes [埃拉托斯特尼筛法]
    • SlidingWindow [滑窗]
    • SudokuSolver [数独]
    • TrappingRainWater [接住雨水]
    • TribonacciNumber [翠波那契数]
    • ZeroOneKnapsack [零一背包]
  • Cache 缓存

  • Array 数组

  • Ciphers 密码学

  • Conversions 转换

  • ProjectEuler 欧拉计划

  • 其他

  • 算法
  • DynamicProgramming 动态规划
jonsam
2022-09-26
目录

LongestValidParentheses [最长合法括号]

# 介绍

给出一个由开括号和闭括号组成的字符串,找出最长的有效括号子串的长度。

一个简单的方法是找到给定字符串的所有子串。对于每个字符串,检查它是否是一个有效的字符串。如果是有效的并且长度超过了目前的最大长度,那么就更新最大长度。我们可以使用堆栈在线性时间内检查一个子串是否有效(详见 Check for Balanced Brackets in an expression (well-formedness) using Stack (opens new window))。这个方案的时间复杂度是 O (n^2).

一个高效的解决方案可以在 O (n) 时间内解决这个问题,其思路是将以前的起始括号的索引存储在一个堆栈中。栈的第一个元素是一个特殊的元素,它提供了有效子串开始前的索引(下一个有效字符串的基数)。

# 实现

# JavaScript

/*
  LeetCode -> 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.
*/

export const longestValidParentheses = (s) => {
  const n = s.length
  const stack = []

  // storing results
  const res = new Array(n).fill(-Infinity)

  for (let i = 0; i < n; i++) {
    const bracket = s[i]

    if (bracket === ')' && s[stack[stack.length - 1]] === '(') {
      res[i] = 1
      res[stack[stack.length - 1]] = 1
      stack.pop()
    } else stack.push(i)
  }

  // summing all adjacent valid
  for (let i = 1; i < n; i++) res[i] = Math.max(res[i], res[i] + res[i - 1])

  // adding 0 if there are none so it will return 0 instead of -Infinity
  res.push(0)
  return Math.max(...res)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

或者:

// JavaScript Program for the above approach
function findMaxLen(str) {
 let n = str.length;
 // Create a stack and push -1 as initial index to it.
 let stk = [];
 stk.push(-1);
 // Initialize result
 let result = 0;

 // Traverse all characters of given string
 for (let i = 0; i < n; i++) {
   // If opening bracket, push index of it
   if (str.charAt(i) == '(') stk.push(i);
   // If closing bracket, i.e.,str[i] = ')'
   else if (stk.length != 0) {
     // Pop the previous opening bracket's index
     stk.pop();
     // Check if this length formed with base of current valid substring is more than max so far
     // 检查该长度与当前有效子串的基数形成的长度是否超过迄今为止的最大值
     result = Math.max(result, i - stk[stk.length - 1]);
     // If stack is empty. push current index as base for next valid substring (if any)
   } else stk.push(i);
 }

 return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 参考

  • Length of the longest valid substring - GeeksforGeeks (opens new window)
编辑 (opens new window)
上次更新: 2022/10/25, 20:46:09
LongestPalindromicSubsequence [最长回文子序列]
MaxNonAdjacentSum [最大非连接子集和]

← LongestPalindromicSubsequence [最长回文子序列] MaxNonAdjacentSum [最大非连接子集和]→

最近更新
01
0-20题解
10-31
02
本章导读
10-31
03
算法与转换:Part1
10-28
更多文章>
Theme by Vdoing | Copyright © 2022-2022 Fancy DSA | Made by Jonsam by ❤
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式