@rkenmi - Reversing words in a string : the double reverse

# Reversing words in a string : the double reverse

## Problem

Reverse all words (separated by space) in a string

## Input

• $$s$$ - a string

## Approach

Nice case and point for really examining the examples.

First, a few examples of reversing words in a string.

"Wu Tang Clan" => "Clan Tang Wu"
"r R r" => "r R r"
"C a c" => "c a C"
"Winter is coming" => "coming is Winter"

It might not come across one to consider completely reversing a string and studying the examples.

If you reverse a sentence, say - "smell u l8r".

You'll have the output: r8l u llems.

At first sight, this doesn't appear to show much. A key visualization here however, is that after reversing the original string, the characters are lined up in the correct positions if we were to reverse all words in a string.

That is, if the final output we are looking for is smell u l8r => l8r u smell, then r8l u llems has the spaces in the correct positions and the alphanumeric characters in relative (but not quite correct) positions.

The trick from here is to reverse only the words in this generated output : r8l => l8r, u => u, llems => smell.

Then the final output becomes: l8r u smell.

Try it yourself!