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

LeetCode 3913: Sort Vowels by Frequency

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

基本資料
#

難易度: medium 第一次嘗試:2026-04-26

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

解題思路
#

子音的位置不動,只重排母音(String 模板四):

  1. 掃一次,記每個母音的次數和第一次出現的位置。
  2. 把母音依序抽出來,用 (-次數, 第一次出現的位置) 排序:次數大的在前,一樣多時先出現的在前。
  3. 再掃一次,遇到母音的位置就依序放回排好的母音。

我的解法
#

class Solution:
    def sortVowels(self, s: str) -> str:
        vowels = set("aeiou")
        count, first = Counter(), {}
        for i, ch in enumerate(s):
            if ch in vowels:
                count[ch] += 1
                first.setdefault(ch, i)
        ordered = sorted((ch for ch in s if ch in vowels), key=lambda ch: (-count[ch], first[ch]))
        it = iter(ordered)
        return "".join(next(it) if ch in vowels else ch for ch in s)

複雜度
#

時間 O(n log n),空間 O(n)。母音只有 5 種,也可以直接照順序展開每種母音的個數,變成 O(n)。

要特別避免的錯誤
#

  • 同樣次數時比的是第一次出現的位置,不是字母順序。
  • 只有母音的位置會被換掉,子音保持原位。

面試口說整理
#

我先數每個母音的次數和第一次出現的位置,把母音抽出來用(負次數, 第一次位置)排序,再依序放回原本母音的位置。時間 O(n log n),因為母音只有 5 種也可以做到 O(n)。

相關文章

LeetCode 522: Longest Uncommon Subsequence II
·1 分鐘
LeetCode Medium Two-Pointers String Sorting Array Hash-Table
LeetCode 522 解題筆記:最長的特殊子序列一定是某個完整字串;依長度由長到短檢查,只要不是其他夠長字串的子序列就是答案
LeetCode 3805: Count Caesar Cipher Pairs
·1 分鐘
LeetCode Medium Math Hash-Table String Counting
LeetCode 3805 解題筆記:把每個字串整串平移到第一個字母是 a,凱薩等價的字串會變成一樣;再數每種正規化結果的配對數
LeetCode 3839: Number of Prefix Connected Groups
·1 分鐘
LeetCode Medium Hash-Table String Counting
LeetCode 3839 解題筆記:前 k 個字元相同的字互相連通,用 word[:k] 當 key 計數;長度不到 k 的字要排除
LeetCode 923: 3Sum With Multiplicity
·3 分鐘
LeetCode Medium Two-Pointers Sorting Hash-Table Counting Array
LeetCode 923 解題筆記:排序後固定第一個數、對撞指針找另外兩個;兩端值相同時用組合數一次算完,不同時把兩端各自的重複數相乘
LeetCode 3639: Minimum Time to Activate String
·2 分鐘
LeetCode Medium Binary-Search Counting String
LeetCode 3639 解題筆記:每個新星號貢獻 (左距離) × (右距離) 個新子字串;或對時間二分
LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 分鐘
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 解題筆記:要減少種類就得整種刪掉,從出現次數最少的開始刪