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

LeetCode 345: Reverse Vowels of a String

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

基本資料
#

難易度: easy 第一次嘗試:2022-08-23

  • 提交紀錄:Accepted ×3

解題思路
#

左右指針各自跳過非母音,兩邊都是母音就交換(Two Pointers 模板一)。母音包含大寫,用一個集合 "aeiouAEIOU" 判斷。

我的解法
#

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = set("aeiouAEIOU")
        a = list(s)
        l, r = 0, len(a) - 1
        while l < r:
            if a[l] not in vowels:
                l += 1
            elif a[r] not in vowels:
                r -= 1
            else:
                a[l], a[r] = a[r], a[l]
                l, r = l + 1, r - 1
        return "".join(a)

複雜度
#

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

要特別避免的錯誤
#

  • 大寫母音也要算。

面試口說整理
#

我用左右指針跳過不是母音的字元,兩邊都是母音時交換再往中間走。時間 O(n)。

相關文章

LeetCode 344: Reverse String
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 344 解題筆記:左右指針交換後往中間走,原地反轉
LeetCode 392: Is Subsequence
·1 分鐘
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 解題筆記:兩個指針,t 的指針一直往前,對上 s 的字元時 s 的指針也前進;兩邊的邊界都要檢查
LeetCode 125: Valid Palindrome
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 125 解題筆記:左右指針跳過非英數字元,再比較小寫是否相同;數字也要算進去
LeetCode 28: Find the Index of the First Occurrence in a String
·1 分鐘
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 解題筆記:在每個起點比對 needle,或直接用 str.find;index 找不到會丟例外
LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 350: Intersection of Two Arrays II
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 解題筆記:保留重複次數的交集,Counter 相交(&)取兩邊次數的較小值