Leetcode 3557. Find Maximum Number of Non Intersecting Substrings

  • [Leetcode 3557. Find Maximum Number of Non Intersecting Substrings](#Leetcode 3557. Find Maximum Number of Non Intersecting Substrings)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题就是一个比较直接的动态规划的题目,我们只需要考察每一个位是否可以作为一个子串的开头,如果可以那么比较其被取用以及不被取用时的较大值将其进行返回,如果不可以,那么直接返回其不被取用时的值即可。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maxSubstrings(self, word: str) -> int:
        n = len(word)
        locs = defaultdict(list)
        for i, ch in enumerate(word):
            locs[ch].append(i)
        
        @lru_cache(None)
        def dp(idx):
            if idx >= n:
                return 0
            ch = word[idx]
            i = bisect.bisect_left(locs[ch], idx+3)
            if i >= len(locs[ch]):
                return dp(idx+1)
            else:
                return max(dp(idx+1), 1 + dp(locs[ch][i] + 1))
        
        return dp(0)

提交代码评测得到:耗时1713ms,占用内存420.2MB。

相关推荐
1白天的黑夜11 小时前
动态规划-931.下降路径最小和-力扣(LeetCode)
c++·算法·leetcode·动态规划
编程绿豆侠2 小时前
力扣HOT100之动态规划:118. 杨辉三角
算法·leetcode·动态规划
weisian1512 天前
力扣经典算法篇-13-接雨水(较难,动态规划,加法转减法优化,双指针法)
算法·leetcode·动态规划
Espresso Macchiato2 天前
Leetcode 3563. Lexicographically Smallest String After Adjacent Removals
动态规划·leetcode hard·leetcode周赛451·leetcode 3563
1白天的黑夜13 天前
动态规划-918.环形子数组的最大和-力扣(LeetCode)
算法·leetcode·动态规划
勤劳的进取家3 天前
论文阅读:Self-Planning Code Generation with Large Language Models
论文阅读·语言模型·动态规划
Espresso Macchiato3 天前
Leetcode 3562. Maximum Profit from Trading Stocks with Discounts
动态规划·背包问题·leetcode hard·leetcode 3562·leetcode周赛451
俺不是西瓜太郎´•ﻌ•`3 天前
动态规划-蓝桥杯-健身
算法·蓝桥杯·动态规划
了不起的杰3 天前
【算法】:动态规划--背包问题
算法·动态规划