Monday, May 15, 2017

Reverse a string III



Problem Statement

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving white space and initial word order.

Link to GitHub : Code



Example 
Input: "do you like my blog"
Output: "golb ym ekil uoy od"

Solution 

  • Load all the strings into a char array
  • Iterate though the char array
  • Have to variables "i" for the start of the string and "j" for the end of the string. 
  • Move "j", till it finds " ".
  • Swap the elements in the string using reverse function
  • Repeat till the end of char array.

public static String cleanSolution(String s)
 {
  //Convert the string to an Array of string
  char [] arr=s.toCharArray();
  for (int i=0;i<=arr.length-1;i++)
  {
    //When i is non space
   if(arr[i]!=' ')
   {
    int j=i;
    while(j+1 < arr.length && arr[j+1]!=' '){
     //Move j to the end
     j++;
    }
    reverse(arr,i,j);
    i=j;
   }
    
  }
  return new String (arr) ;
 }
 //Function to reverse a string
 public static void reverse(char [] ca,int i,int j)
 {
  for(;i<j;i++,j--){
   char temp=ca[i];
   ca[i]=ca[j];
   ca[j]=temp;
  }
  
 }

Iteration


No comments:

Post a Comment