↓快轉到主要內容
  1. LeetCode/

LeetCode 3545: Minimum Deletions for At Most K Distinct Characters

·1 分鐘· ·
LeetCode Easy Greedy Hash-Table String Sorting Counting
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-05-11

  • 提交紀錄:Accepted(一次通過)

解題思路
#

只刪掉某種字元的一部分,種類數不會變少,所以要刪就整種刪掉。有 m 種、最多留 k 種,就要刪掉 m - k 種,挑出現次數最少的那幾種刪,刪的字元數最少。

我的解法
#

class Solution:
    def minDeletion(self, s: str, k: int) -> int:
        freq = sorted(Counter(s).values())
        drop = max(0, len(freq) - k)
        return sum(freq[:drop])

我當時把 Counter 依次數排序成 dict,再數到 len - k 個;排序 values() 就夠了。

複雜度
#

時間 O(n + σ log σ),σ 是字元種類數(最多 26),空間 O(σ)。

要特別避免的錯誤
#

  • 種類本來就 <= k 時 len(freq) - k 是負的,freq[:負數] 會從後面切掉,要先跟 0 取 max。

面試口說整理
#

部分刪除不會減少種類,所以只能整種刪。我統計每種字元的次數、由小到大排序,刪掉最少的 m - k 種,加總它們的次數。時間 O(n)。

相關文章

LeetCode 3541: Find Most Frequent Vowel and Consonant
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 3541 解題筆記:數每個字元的次數,母音取最大、子音取最大再相加;沒有的那一類算 0
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 分鐘
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 解題筆記:每次操作會讓最小的正數那一群變成 0,所以次數就是不同的正數有幾種
LeetCode 1189: Maximum Number of Balloons
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 1189 解題筆記:每個字母可以組幾個 balloon 是 次數 // 需要數,l 和 o 需要兩個,取最小值
LeetCode 884: Uncommon Words from Two Sentences
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 884 解題筆記:把兩個句子合起來數每個單字的次數,只出現一次的就是答案
LeetCode 819: Most Common Word
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 解題筆記:標點換成空白、全部轉小寫再切單字,計數後找出不在 banned 裡的最多的那個