Day 17 of 100 Days of DSA
Day 17: Sorting Vowels in a String
Today, as part of my 100 days of DSA challenge, I tackled a medium-level problem from LeetCode. The task was to sort the vowels in a given string. Let me walk you through how I approached and solved this problem.
Firstly, I created an empty string called vowel
to store all the vowels from the given input string. I used a loop to iterate through each character in the input string. If the character was a vowel (either lowercase or uppercase), I added it to the vowel
string.
After collecting all the vowels, I sorted them in non-decreasing order using the sort
function.
Now, I needed to replace the original string's vowels with the sorted vowels. To do this, I used another loop to traverse the original string. If the current character was a vowel, I replaced it with the corresponding character from the sorted vowel
string. I kept track of my position in the sorted vowel
string using an index variable j
.
Here's a breakdown of the code:
class Solution {
public:
string sortVowels(string str) {
// Step 1: Collect vowels from the given string
string vowel = "";
for(int i = 0; i < str.size(); i++) {
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
vowel += str[i];
}
}
// Step 2: Sort the collected vowels
sort(vowel.begin(), vowel.end());
// Step 3: Replace original string's vowels with sorted vowels
int j = 0;
for(int i = 0; i < str.size(); i++) {
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
str[i] = vowel[j++];
}
}
// Step 4: Return the modified string
return str;
}
};
In summary, this code efficiently sorts the vowels in a given string by collecting them, sorting them, and then replacing the original string's vowels with the sorted ones.