Arrays: Given a string, reverse all the vowels in the string

Example 1:

Input: hello
Output: holle

Example 2:

Input: prodevelopertutorial
Output: pradivolupertotereol

We can solve this problem in 2 methods.

Method 1: By using STL functions

In this method we use “find_first_of” and “find_last_of”

find_first_of(“characters_to_search_for”, start_from_index) : It will return the position of the first character it matches from the list of characters to match for.

find_last_of(“characters_to_search_for”, start_from_index) : It will return the position of the last character it matches from the list of characters to match for.

Take 2 pointers “i” starts from the start of the string and “j” starts from the end of the string.

Once we find the elements, we swap both the elements.
We terminate the loop once “i > j”.

Method 2: Without using STL functions.

In this method we use find() to check if the character is an vowel.
Then take 2 pointers, on start from beginning and another from end. Then once you find both the vowels swap the characters.

Solution in C++

#include<iostream>
#include<string>
#include<set>

using namespace std;


string reverse_vowels_method_1(string s) 
{
    int i = 0;
    int j = s.size() - 1;

    while (i < j) 
    {
        i = s.find_first_of("aeiouAEIOU", i);
        j = s.find_last_of("aeiouAEIOU", j);
        if (i < j) 
        {
            swap(s[i++], s[j--]);
        }
    }
    return s;
}



string reverse_vowels_method_2(string s) 
{
    set<char> vowels = {'a','e','i','o','u','A','E','I','O','U'};
    int i= 0;
    int j = s.size()-1;

    while(i<j)
    {
        while(vowels.find(s[i])==vowels.end()) i++;
        while(vowels.find(s[j])==vowels.end()) j--;
        if(i>=j) break;
        swap(s[i],s[j]);
        i++;
        j--;
    }
    return s;
}

int main()
{
    string str = "prodevelopertutorial";
    string result = reverse_vowels_method_1(str);

    cout<<"The string is = "<<str<<". The result by using Method 1 is = "<<result<<endl;

    result = reverse_vowels_method_2(str);
    cout<<"The string is = "<<str<<". The result by using Method 2 is = "<<result<<endl;


    return 0;
}

Output:

The string is = prodevelopertutorial. The result by using Method 1 is = pradivolupertotereol
The string is = prodevelopertutorial. The result by using Method 2 is = pradivolupertotereol

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *