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 Macchiato2 天前
Leetcode 3702. Longest Subsequence With Non-Zero Bitwise XOR
leetcode medium·异或操作·leetcode 3702·leetcode周赛470
Espresso Macchiato3 天前
Leetcode 3694. Distinct Points Reachable After Substring Removal
滑动窗口·leetcode medium·leetcode双周赛166·leetcode 3694
Espresso Macchiato3 天前
Leetcode 3698. Split Array With Minimum Difference
leetcode medium·分类讨论·leetcode周赛469·leetcode 3698
Brookty15 天前
【算法】滑动窗口(一)-长度最小的子数组
java·学习·算法·力扣·滑动窗口
伟大的车尔尼23 天前
滑动窗口题目:删除子数组的最大得分
滑动窗口
递归尽头是星辰24 天前
双指针与滑动窗口算法精讲:从原理到高频面试题实战
算法·双指针·滑动窗口·子串/子数组问题
ゞ 正在缓冲99%…1 个月前
leetcode438.找到字符串中所有字母异位词
leetcode·滑动窗口
3Cloudream1 个月前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
HUIMU_1 个月前
DAY20-新世纪DL(DeepLearning/深度学习)战士:终(目标检测/YOLO)3
深度学习·yolo·目标检测·滑动窗口·非极大值抑制·交并比·bouding box
Espresso Macchiato1 个月前
Leetcode 3665. Twisted Mirror Path Count
动态规划·leetcode medium·leetcode 3665·leetcode双周赛164