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

LeetCode 3541: Find Most Frequent Vowel and Consonant

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

基本資料
#

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

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

解題思路
#

用 Counter 數每個字元,再分成母音和子音兩類各取最大值(String 模板四)。某一類完全沒有時算 0,用 max(..., default=0)。

我的解法
#

我當時先把 Counter 依次數排序再掃一遍;排序是多餘的,直接取最大就好:

class Solution:
    def maxFreqSum(self, s: str) -> int:
        vowels = set("aeiou")
        cnt = Counter(s)
        best_v = max((v for c, v in cnt.items() if c in vowels), default=0)
        best_c = max((v for c, v in cnt.items() if c not in vowels), default=0)
        return best_v + best_c

複雜度
#

時間 O(n),空間 O(1)(最多 26 種字元)。

要特別避免的錯誤
#

  • 某一類沒有字元時,max 對空序列會報錯,要給 default=0。

面試口說整理
#

我數每個字元的次數,母音裡取最大、子音裡取最大,相加回傳;沒有的那一類算 0。時間 O(n)。

相關文章

LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
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 裡的最多的那個
LeetCode 383: Ransom Note
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 383 解題筆記:ransomNote 每個字元的需求數量都不能超過 magazine 的數量;Counter 相減為空就成立
LeetCode 387: First Unique Character in a String
·1 分鐘
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 解題筆記:先計數,再從左到右找第一個次數是 1 的字元