Monday, 5 February 2018

C++ Program to Reverse the Vowels of a String

C++ Program to reverse the vowels of a string is given below. Approach is simple, we will use two pointer approach. First we will initialize a counter at the start of the string and the other one is at the end of the string. Time complexity of the program given below is O(n) and space complexity is O(1).

ALGORITHM:

1. set i=0 and j= string.size()-1
2. while(i<j):
3.          if string[i]==vowel (both uppercase and lowercase):
4.                  do while(j>i):
5.                         if string[j]==vowel:
6.                                 swap string[i] and string[j];
7.                                j--;
8.                         endIf
9.                  end While
10.        endIf
11.        i++;
12. endWhile


PROGRAM:

#include <bits/stdc++.h>
using namespace std;

void reverse_vowels(string &s){
 
       int i=0;
          int j=s.size()-1;
          
        /*start of outer loop*/
          while(i<j){
                if(  s[i]=='a' || s[i]=='e' || 
                     s[i]=='i' || s[i]=='o' || 
                     s[i]=='u' || s[i]=='A' || 
                     s[i]=='E' || s[i]=='O' || 
                     s[i]=='I' || s[i]=='U'
                  ){
                      /*start of inner loop*/
                       while(j>i)
                       {
                           if( 
                               s[j]=='a' || s[j]=='e' || 
                               s[j]=='i' || s[j]=='o' || 
                               s[j]=='u' || s[j]=='A'|| 
                               s[j]=='E' || s[j]=='O'||
                               s[j]=='I'||s[j]=='U'
                             ){
                                 char ch=s[j];
                                 s[j]=s[i];
                                 s[i]=ch;
                                 j--;
                                 break;
                             }
                          j--;
                       }/*end of inner loop*/
                       
                   }
                   i++;
          }/*end of outer loop*/
          
}
int main(){
  
   int t;
   cout<<"\nEnter the number of test cases: \n";
   cin>>t;
   while(t--){

        cout<<"\n\nEnter the string: \n";
        string s;
        cin>>s;

        /*function call to reverse the vowerls*/
        reverse_vowels(s);

        cout<<"\nThe string after reversing of all the vowels is:\n";
        cout<<s;
        cout<<"\n\n";

   }
   return 0;
}

OUTPUT:



EmoticonEmoticon