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

LeetCode 3775: Reverse Words With Same Vowel Count

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

基本資料
#

難易度: medium 第一次嘗試:2026-01-24

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

解題思路
#

  1. 用空白切開字串。
  2. 數第一個字的母音數 target。
  3. 第一個字不動,後面每個字如果母音數等於 target 就反轉,否則不動。

反轉一個字可以用切片 word[::-1],或用對撞指針交換。

我的解法
#

class Solution:
    def reverseWords(self, s: str) -> str:
        def vowels(word: str) -> int:
            return sum(ch in "aeiou" for ch in word)

        words = s.split(" ")
        target = vowels(words[0])
        return " ".join([words[0]] + [w[::-1] if vowels(w) == target else w for w in words[1:]])

原本的版本數母音時,對每個母音呼叫一次 word.count(v),掃了五遍字串;這裡改成掃一遍。另外原本用「res 是不是空的」判斷是不是第一個字,這裡直接把第一個字分開處理。

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 把第一個字也反轉:題目只處理第一個字之後的字。

面試口說整理
#

我先用空白切開,數出第一個字的母音數,後面的字母音數一樣就反轉、不一樣就保留,最後再用空白接回去。每個字元只看常數次,時間 O(n)。

相關文章

LeetCode 2105: Watering Plants II
·1 分鐘
LeetCode Medium Two-Pointers Simulation Array
LeetCode 2105 解題筆記:Alice 從左、Bob 從右,對撞指針模擬澆水;相遇在同一株時由水比較多的人澆
LeetCode 1616: Split Two Strings to Make Palindrome
·2 分鐘
LeetCode Medium Two-Pointers String Greedy
LeetCode 1616 解題筆記:外側用 a 的前綴配 b 的後綴貪心比對,配不下去時,剩下的中間段必須整段在 a 或 b 裡是回文;兩個方向都要檢查
LeetCode 1750: Minimum Length of String After Deleting Similar Ends
·1 分鐘
LeetCode Medium Two-Pointers String
LeetCode 1750 解題筆記:兩端字元相同時,各自把同一段相同字元全部吃掉;整段都是同一個字元時可以刪光
LeetCode 165: Compare Version Numbers
·1 分鐘
LeetCode Medium Two-Pointers String
LeetCode 165 解題筆記:用 . 切開後轉成整數逐段比較,比較短的版本缺的段當作 0
LeetCode 3703: Remove K-Balanced Substrings
·2 分鐘
LeetCode Medium Stack String Simulation
LeetCode 3703 解題筆記:反覆 replace 是 O(n^2);stack 存 (字元, 連續個數),湊到 k 個 ( 加 k 個 ) 就整段消掉
LeetCode 3612: Process String with Special Operations I
·1 分鐘
LeetCode Medium String Simulation
LeetCode 3612 解題筆記:用 list 模擬四種操作;判斷 * 時要把「結果非空」寫在分支裡面,不然 * 會被當成字母加進去