Leetcode 3085. Minimum Deletions to Make String K-Special

  • Leetcode 3085. Minimum Deletions to Make String K-Special
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接:3085. Minimum Deletions to Make String K-Special

1. 解题思路

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

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

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

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

2. 代码实现

给出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。

你可能感兴趣的:(leetcode笔记,leetcode,3085,leetcode周赛389,leetcode,medium,leetcode题解,滑动窗口)