How to Reverse Vowels of a String in C/C++?


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).

1
2
3
4
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';
}
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}
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) —

GD Star Rating
loading...
193 words
Last Post: The Basic Calculator in C/C++
Next Post: Break a Sentence into Words (Word Break Algorithms) - DFS, BFS and DP

The Permanent URL is: How to Reverse Vowels of a String in C/C++?

Leave a Reply