Type like pro

Index

Reverse the words of a sentence

Reverse the words of a sentence

Problem


Reverse the words in a given sentence. Words are always delimited by spaces. For example if the given word is "reverse words of a sentence". The output will be "sentence a of words reverse"

Solution


Reverse the complete sentence and then reverse every part of sentence which is delimited by spaces. 


Code

public class ReverseWordsInSentence
{
 public static void main(String[] args)
 {
  String str = "reverse words of a sentence";
  String result = reverseWords(str);
  System.out.println(result);
 }

 private static String reverseWords(String str)
 {
  char[] chars = str.toCharArray();
  reverse(chars, 0, chars.length - 1);
  int wordStart = 0;
  int wordEnd = 0;
  while (wordEnd < chars.length)
  {
   if (chars[wordEnd] == ' ')
   {
    reverse(chars, wordStart, wordEnd - 1);
    wordStart = wordEnd + 1;
   }
   wordEnd++;
  }
  reverse(chars, wordStart, wordEnd - 1);
  return new String(chars);
 }

 private static void reverse(char[] chars, int i, int j)
 {
  while (i < j)
  {
   char temp = chars[i];
   chars[i] = chars[j];
   chars[j] = temp;
   i++;
   j--;
  }
 }
}