557. Reverse Words in a String III


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.

Example 1:

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.


Solution


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.

Complexity Analysis

  • 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]

Algorithm

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.

Complexity Analysis

  • Time complexity : . where is the length of the string.
  • Space complexity : . of size is used.

Approach #3 Using StringBuilder and reverse method [Accepted]

Algorithm

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.

Complexity Analysis

  • 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