Reverse Vowels of a String

Desicription

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

1
2
Input: "hello"
Output: "holle"

Example 2:

1
2
Input: "leetcode"
Output: "leotcede"

Note:

The vowels does not include the letter “y”.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
std::string reverseVowels(const std::string& s) {
auto vowels = std::string();
for(auto c : s) {
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
vowels += c;
}
}
std::reverse(vowels.begin(), vowels.end());

auto res = std::string();
int index = 0;
for(auto c : s) {
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
res += vowels[index++];
} else {
res += c;
}
}

return res;
}
};