Sort Vowels in a String
The task requires sorting the vowels in a given string, s
, while keeping the consonants in their original places. Here’s a Python solution for the problem:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| class Solution:
def sortVowels(self, s: str) -> str:
vowels = [c for c in s if c in 'aeiouAEIOU'] # Extract all vowels
vowels.sort() # Sort the vowels
result = [] # Initialize the result array
j = 0 # Index for the vowels list
for c in s: # Iterate through the original string
if c in 'aeiouAEIOU': # If it's a vowel
result.append(vowels[j]) # Append the sorted vowel
j += 1 # Increment the index for vowels
else:
result.append(c) # If it's a consonant, keep it in its place
return ''.join(result) # Return the result as a string
|
This code first extracts all the vowels from the string s
and sorts them. Then it iterates through the original string and builds the result by placing the sorted vowels and original consonants in their respective positions.