Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
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.\n\n
Time complexity : . where is the length of the string.\n
Space complexity : . of size is used.\n
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.\n\n
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.\n\n
Analysis written by: @vinod23\n