Wednesday, May 17, 2017

Reverse Vowels of a String

Problem Statement

Write a function that takes a string as input and reverse only the vowels of a string.

Link to GitHub :Code


Example


Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".

Solution

  • Store all the vowel character in a string
  • We need 2 variables head and tail
  • Head is the initial position and tail is the last position in the array
  • Increment the header if we do not find vowel character .Decrement the tail if we do not find the vowel character.
  • Loop through the array till we find tail is greater than head and swap the tail with the head where we find vowel character
  • Return the new string 


public static String get(String s)
 {
  //Check for empty and null condition
  if(s==null || s.length()==0) return s;
  //Store all the vowels in a variable
  String vowels="aeiouAEIOU";
  //Convert the string into character array
  char [] c=s.toCharArray();
  // we need 2 pointers. One for the hed and other for the tail
  int head=0;
  int tail=c.length-1;
  //Loop through the array to reverse the string
  while (head <tail)
  {
   //Increment head if we do not find vowels
   while(head<tail && !vowels.contains(c[head]+""))
   {
    head++;
   }
   //Decrement tail, if we do not find vowels
   while(head<tail && !vowels.contains(c[tail]+""))
   {
    tail--;
   }
   char temp=c[head];
    c[head]=c[tail];
    c[tail]=temp;
    
   head++;
   tail--;
  }
  
  return new String(c);

No comments:

Post a Comment