Given an input string, reverse the string word by word.

Example 1:

Input: “the sky is blue” Output: “blue is sky the”

Example 2:

Input: ” hello world! ” Output: “world! hello” Explanation: Your reversed string should not contain leading or trailing spaces.

Example 2:

Input: “a good example” Output: “example good a” Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Solution

We can use Space as a tokenizer to split the string, Iterate array from end element and accumulate none empty string to the result string.

Code

Output

blue is sky the

We encourage you to write a comment if you have a better solution or having any doubt on the above topic.

Leave a Reply

Your email address will not be published. Required fields are marked *