Leetcode 3085. Minimum Deletions to Make String K-Special

  • [Leetcode 3085. Minimum Deletions to Make String K-Special](#Leetcode 3085. Minimum Deletions to Make String K-Special)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题思路上来说的话我们只需要统计一下word当中所有的字符出现的频次,然后依次排序,我们只需要考察各个删除方案使得所有存在的频次之间的差值不多于 k k k即可。

而对于各个具体的删除方案的考察,我们只需要用一个滑动窗口来考察一下一下各个字母作为起点时允许的频次范围并计算一下对应方案下所需要删除的元素个数即可。

显然,对于任意时刻,左边界左侧的字符全部不采用,而右边界右侧的元素则全部替换为范围上界即可。

且不难看出,左右边界的移动必然都是单调的。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def minimumDeletions(self, word: str, k: int) -> int:
        n = len(word)
        cnt = Counter(word)
        cnt = sorted(cnt.values())
        i,j,m = 0,0,len(cnt)
        ans, s = n, 0
        while i < m:
            while j < m and cnt[j]-cnt[i] <= k:
                s += cnt[j]
                j += 1
            ans = min(ans, n-(s+(cnt[i]+k)*(m-j)))
            s -= cnt[i]
            i += 1
        return ans

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

相关推荐
Espresso Macchiato1 天前
Leetcode 3568. Minimum Moves to Clean the Classroom
剪枝·广度优先遍历·leetcode medium·堆排·leetcode周赛452·leetcode 3568
Espresso Macchiato5 天前
Leetcode 3567. Minimum Absolute Difference in Sliding Submatrix
leetcode·leetcode medium·leetcode周赛452·leetcode 3567
Espresso Macchiato5 天前
Leetcode 3566. Partition Array into Two Equal Product Subsets
动态规划·leetcode medium·leetcode 3566·leetcode周赛452
GEEK零零七6 天前
Leetcode 159. 至多包含两个不同字符的最长子串
算法·leetcode·滑动窗口
Espresso Macchiato11 天前
Leetcode 3557. Find Maximum Number of Non Intersecting Substrings
动态规划·leetcode medium·leetcode 3557·leetcode双周赛157
Espresso Macchiato19 天前
Leetcode 3552. Grid Teleportation Traversal
广度优先遍历·leetcode medium·leetcode周赛450·leetcode 3552·堆排
Espresso Macchiato20 天前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
Espresso Macchiato23 天前
Leetcode 3543. Maximum Weighted K-Edge Path
leetcode·leetcode medium·图遍历·leetcode 3543·leetcode双周赛156
卷卷的小趴菜学编程1 个月前
算法篇-----滑动窗口
数据结构·算法·双指针·滑动窗口·哈希表·数组相关
满怀10151 个月前
【数据通信完全指南】从物理层到协议栈的深度解析
5g·滑动窗口·数据封装·crc校验·qam调制