Leetcode 3316. Find Maximum Removals From Source String

  • [Leetcode 3316. Find Maximum Removals From Source String](#Leetcode 3316. Find Maximum Removals From Source String)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题思路上的话就是一个动态规划的题目,我们仿照lcs,考察每一个位置是否可以drop即可。

而关于lcs算法,网上有很多介绍文章,这里就不过多赘述了。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maxRemovals(self, source: str, pattern: str, targetIndices: List[int]) -> int:
        n, m = len(source), len(pattern)
        targets = set(targetIndices)

        @lru_cache(None)
        def dp(i, j):
            if j >= m:
                return len([idx for idx in range(i, n) if idx in targets])
            if i >= n:
                return -math.inf
            if i in targets:
                if source[i] == pattern[j]:
                    return max(dp(i+1, j+1), 1 + dp(i+1, j))
                else:
                    return 1 + dp(i+1, j)
            else:
                if source[i] == pattern[j]:
                    return dp(i+1, j+1)
                else:
                    return dp(i+1, j)
                
        remove = dp(0, 0)
        return remove if remove != -math.inf else 0

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

相关推荐
YuTaoShao1 天前
【LeetCode 每日一题】1277. 统计全为 1 的正方形子矩阵
算法·leetcode·矩阵
野犬寒鸦1 天前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode
阿昭L1 天前
leetcode两数之和
算法·leetcode
Lris-KK1 天前
【Leetcode】高频SQL基础题--1164.指定日期的产品价格
sql·leetcode
Swift社区1 天前
Swift 解法详解:LeetCode 371《两整数之和》
开发语言·leetcode·swift
Swift社区1 天前
Swift 解法详解 LeetCode 362:敲击计数器,让数据统计更高效
开发语言·leetcode·swift
一只鱼^_1 天前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
小刘的AI小站1 天前
leetcode hot100 二叉搜索树
算法·leetcode
自信的小螺丝钉1 天前
Leetcode 876. 链表的中间结点 快慢指针
算法·leetcode·链表·指针
红豆怪怪1 天前
[LeetCode 热题 100] 32. 最长有效括号
数据结构·python·算法·leetcode·动态规划·代理模式