Approach #1 Simple Solution[Accepted]
The first method is really simple. We simply split up the given string based on whitespaces and put the individual words in an array of strings. Then, we reverse each individual string and concatenate the result. We return the result after removing the additional whitespaces at the end.
Time complexity : . where is the length of the string.
Space complexity : . of size is used.
Approach #2 Without using pre-defined split and reverse function [Accepted]
We can create our own split and reverse function. Split function splits the string based on the delimiter " "(space) and returns the array of words. Reverse function returns the string after reversing the characters.
- Time complexity : . where is the length of the string.
- Space complexity : . of size is used.
Approach #3 Using StringBuilder and reverse method [Accepted]
Instead of using split method, we can use temporary string to store the word. We simply append the characters to the until
' ' character is not found. On getting
' ' we append the reverse of the to the resultant string . Also after completion of loop , we still have to append the of the (last word) to the string.
Below code is inspired by @ApolloX.
- Time complexity : . Single loop upto is there, where is the length of the string.
- Space complexity : . and size will grow upto .
Analysis written by: @vinod23