Reverse Vowels of a string in C++

C++Server Side ProgrammingProgramming

Given a string, the task is to reverse all the vowels present in the given string. For example,

Input-1

a = “tutor”

Output

totur

Explanation − Reversing the string “tutor” will generate the output as “totur.

Input-2

a = “mathematics”

Output

mithametacs

Explanation − Reversing the string “mathematics” will generate the output as “mithametacs”.

Approach to solve this problem

Given a string, we have to reverse all the vowels present in it. There are several approaches to solve this particular problem but we have to solve this in linear time O(n).

Thus, the better method to solve this problem is to use the Two-Pointer approach in which we will take two pointers low and high which will be pointing initially to the leftmost element and rightmost element. In two nested loops, we will check if the leftmost character is a vowel and the rightmost character is vowel also then swap the element and move the right pointer.

  • Take input a string.

  • A Boolean function to check if the character is a vowel or not.

  • A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string.

  • Initialize two pointers low and high which point to ‘0’ and last character respectively.

  • Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer.

  • Repeating the steps until all the characters of the string are not visited.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isVowel(char ch) {
   return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
string reverseVowel(string &s){
   int low = 0;
   int high = s.size() - 1;
   while (low < high) {
      while (low < high && !isVowel(s[low])) {
         low ++;
      }
      while (low < high && !isVowel(s[high])) {
         high --;
      }
      swap(s[low++], s[high--]);
   }
   return s;
}
int main(){
   string a= "tutorialspoint";
   string ans= reverseVowel(a);
   cout<<ans;
   return 0;
}

Output

Running the above code will generate the output as,

titorailspount

Since the given string “tutorialspoint” contains vowels, after reversing the vowels, it will generate the output as, “titorailspount”.

raja
Published on 05-Feb-2021 10:22:25
Advertisements