Reverse words in a sentence
  • Posted: 5 years ago
  • Edit
  • answers (1)
  • views (2838)

Write a function to reverse the order of a sentence word by word without using any other data
structure. \( E.g \), if the input is `Algoqueue is the best website', the result will be `website best the is Algoqueue'.


Posted Answers

< Using split function >


  • Split the whole sentence word by word and store them in a String array.
  • Iterate through the array from end to beginning and add each word to the result.

public static void revSentenceWordByWord(String input){

/* Split word by word */
string[] word = input.split(" ");
StringBuilder result = new StringBuilder();
/* Iterate from end to beginning */
for(int i = word.length - 1; i >= 0 ; i--)
result.append(word[i]);
result.append(" ");

System.out.println(result.toString());

}



< Without using split function >

  • Reverse the given string (the whole sentence).
  • Reverse each word in the string.

public static char[] revSentenceWordByWord(char[] input){

int beginIndex = 0;
int endIndex = input.length - 1;
if (endIndex > 1){

/* Reverse the whole sentence */
input = reverseString(input, 0, endIndex);

/* Reverse each word in the reversed sentence */
for (endIndex = 0; endIndex < = input.length; endIndex++){
if (endIndex == input.length || input[endIndex] == ' '){
input = reverseString(input, beginIndex, endIndex - 1);
beginIndex = endIndex + 1;
}
}
}
return input;
}

public static char[] reverseString(char[] input, int beginIndex, int endIndex){

char temp;
while(beginIndex < endIndex){

temp = input[beginIndex];
input[beginIndex++] = input[endIndex];
input[endIndex--] = temp;
}
return input;
}

You need to Sign In to post your solution.