Reverse Words

March 8, 2011

After we solved the reverse-words problem in an exercise a few weeks ago, a reader complained that the suggested solution was too simple because it used library functions to split the words and later to rejoin them; he also thought the exercise should include a restriction that the string had to be reversed in-place. I’m not sure about either of the objections, but we’ll take the opportunity to revisit a classic interview question. We’ll also eliminate the letters-only and single-space-between-words restrictions of the original exercise from Google. Thus, here are some sample inputs and their associated outputs; note especially the placements of leading and trailing spaces:

"" => ""
" " => " "
"  " => "  "
"hello" => "hello"
"hello " => " hello"
" hello" => "hello "
"the quick brown fox" => "fox brown quick the"
"the quick  brown fox" => "fox brown  quick the"
"the quick  brown 42 fox!" => "fox! 42 brown  quick the"

Your task is to write a reverse-words function given the definition and restrictions stated above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2