Write a function to reverse only the vowels of a string. Example: Given s = “hello”, return “holle”.
A vowel is one of the following 10 letters (both uppercase and lowercase).
inline bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
To swap only the vowels we need two index pointers, pointing to the start and the end of the string, only stopping at the vowels until they meet in the middle.
string reverseVowels(string s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
while (i < j && !isVowel(s[i])) {
i ++;
}
while (i < j && !isVowel(s[j])) {
j --;
}
swap(s[i++], s[j--]);
}
return s;
}
O(n) time complexity and O(1) space complexity.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: The Basic Calculator in C/C++
Next Post: Break a Sentence into Words (Word Break Algorithms) - DFS, BFS and DP