Split it and then add it to a new String
in reverse order.
String s = " I live in India";
String[] split = s.split(" ");
String result = "";
for (int i = split.length - 1; i >= 0; i--) {
result += (split[i] + " ");
}
System.out.println(result.trim());
This prints:
India in live I
Although short and straight-forward, this solution is not really effective in terms of time and memory. It somewhat depends on how the input is given (as a String
or as something else) and whether we can modify the input in order to save computation resources.
Let's assume the sentence is given as an array of characters and we are allowed to modify it. We can then follow the following approach, which brings linear time (O(n)
) and constant (O(1)
) memory complexity:
What we will have as input would be:
char[] array = {'I',' ','l','i','v','e',' ','i','n',' ','I','n','d','i','a'};
Let's write a method that takes a char[]
array and reverses the elements from start
to end
in-place:
void reverse(char[] array, int start, int end) {
while (start < end) {
char temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
First, we will reverse the whole array (in-place), using this method.
You can notice that after the reversal the words in the sentence are ordered in the desired (reversed) way. The problem is that each word is reversed:
{'a','i','d','n','I',' ','n','i',' ','e','v','i','l',' ','I'}
Let's now iterate the array from left to the right. We will reverse each word in-place, like we initially reversed the whole array. In order to do that, we need to keep an index (start
), telling where does a word start and every time we encounter a space (' '
) we will trigger a reverse between start
and the character before the space. This way we will keep the desired order of words, but we will also have the characters in the words properly ordered.
The code should be self-explanatory:
void reverseSentence(char[] array) {
int n = array.length;
reverse(array, 0, n - 1);
int start = 0;
for (int i = 0; i < n; i++) {
if (array[i] == ' ') {
reverse(array, start, i - 1);
start = i + 1;
}
}
}
Calling this on the initial array
, we get:
{'I','n','d','i','a',' ','i','n',' ','l','i','v','e', ' ','I'}
We can further construct a String
out of it, or just print it. In any case, the sentence is reversed as desired.
This has linear complexity (O(n)
), because each character is part of a reverse exactly once and is being tested for being a space exactly once.
As for memory-usage, we used only one additional variable (start
), which makes the total memory complexity a constant (O(1)
).