LeetCode 筆記 - 2785. Sort Vowels in a String

題目在此 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

相關文章