Sort Vowels in a String [Medium] — Extraction and Replace
Advertisement
Problem Statement
Given string s, sort the vowels in non-decreasing order while keeping all consonants in their original positions.
Input: "lEetcOde" → Output: "lEOtcede"
Solutions
Python
def sortVowels(s: str) -> str:
vowels_set = set('aeiouAEIOU')
vowels = sorted(c for c in s if c in vowels_set)
res = list(s)
j = 0
for i, c in enumerate(res):
if c in vowels_set:
res[i] = vowels[j]; j += 1
return ''.join(res)
C++
string sortVowels(string s) {
string v="aeiouAEIOU", vs="";
for(char c:s) if(v.find(c)!=string::npos) vs+=c;
sort(vs.begin(),vs.end());
int j=0;
for(char& c:s) if(v.find(c)!=string::npos) c=vs[j++];
return s;
}
Complexity
- Time: O(n log n), Space: O(n)
Advertisement