Reverse Vowels of a String - CPP Solution

1. Introduction

This blog post addresses a unique and interesting string manipulation problem in C++: reversing only the vowels in a given string. The challenge lies in identifying the vowels in the string and reversing their order while keeping the rest of the characters intact.

Problem

Given a string s, the task is to reverse only all the vowels in the string and return it. The vowels ('a', 'e', 'i', 'o', 'u') can appear in both lower and upper cases and may be present more than once in the string.

2. Solution Steps

1. Create a set to efficiently check whether a character is a vowel.

2. Use two pointers: one starting at the beginning and the other at the end of the string.

3. Move the pointers towards each other, stopping at each vowel.

4. Swap the vowels at these two pointers.

5. Continue until the two pointers meet or cross.

6. By doing this, only the vowels in the string are reversed.

3. Code Program

#include <iostream>
#include <unordered_set>
using namespace std;

// Function to check if a character is a vowel
bool isVowel(char c) {
    static const unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
    return vowels.count(c);
}

// Function to reverse only the vowels in a string
string reverseVowels(string s) {
    int start = 0, end = s.length() - 1;

    while (start < end) {
        // Move start pointer to the next vowel
        while (start < end && !isVowel(s[start])) {
            start++;
        }

        // Move end pointer to the previous vowel
        while (start < end && !isVowel(s[end])) {
            end--;
        }

        // Swap the vowels
        swap(s[start], s[end]);
        start++;
        end--;
    }

    return s;
}

int main() {
    string s = "hello";
    cout << "Reversed vowels: " << reverseVowels(s) << endl;
    return 0;
}

Output:

Reversed vowels: holle

Explanation:

1. The input string "hello" is processed to reverse only the vowels.

2. The function identifies vowels 'e' and 'o' and reverses their positions.

3. Two pointers are used to find vowels from the beginning and end of the string.

4. The vowels are then swapped, and the pointers are moved towards each other.

5. The process continues until all vowels have been reversed in their positions, resulting in the string "holle".

6. This approach efficiently reverses only the vowels in the string while leaving other characters unchanged.


Comments