LeetCode 筆記 - 2785. Sort Vowels in a String

在這篇 LeetCode 第 2785 題的筆記中,我們探討了如何針對字串中的母音進行局部排序。解題思路相當直觀:先將所有母音提取出來並依 ASCII 順序排好,再重新填回原字串的母音位置。本文透過簡明的 Python 實作,示範了如何優雅地處理這類字串操作問題。

發佈
閱讀
約 1 分鐘
字數
153

題目在此 2785. Sort Vowels in a String

給定一個字串,請把裡面的母音按照 ASCII 的順序排序。

解題思維

這題就是把母音撈出來之後排序,再塞回去。image 106

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def sortVowels(self, s: str) -> str:

if (size := len(s)) == 1:
return s

vowels = set('aeiouAEIOU')
s_vowels = [c for c in s if c in vowels]
s_vowels.sort()

vowel_index = 0
result = ''
for c in s:
if c in vowels:
result += s_vowels[vowel_index]
vowel_index += 1
else:
result += c

return result
image 106

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟