151_Reverse Words in a String

[medium]

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

Note: need to make sure that the string only contains letters and spaces.

Test case 1 (easy)

Input: "the weather is good"
Output: "good is weather the"

Test case 2 (with spaces at the beginning and the end)

Input: "   the weather is good   "
Output: "good is weather the"

Test case 3 (only spaces in the string)

Input: "      "
Output: ""

Test case 4 (empty string)

Input: ""
Output: ""

Test case 5 (more than one space between words)

Idea 1

  • extract all words in to a list

  • reverse the list

  • join strings in the list with space

Complexity 1

  • Time: O(n)O(n)

  • Space: O(n)O(n)

Solution 1_v1 (with build-in functions split(), reverse(), join())

Solution 1_v2 (write split(), use build in reverse(), join())

Idea 2

  • reverse the entire string

  • loop over the string, reverse the words, append space after each word, and neglect all the spaces.

Complexity 2

  • Time: O(n)O(n)

  • Space: O(n)O(n)

Solution 2

Idea 3

  • reverse the entire string

  • loop over the string, reverse the words, append space after each word, and neglect all the spaces.

  • do everything in-place

Complexity 3

  • Time: O(n)O(n)

  • Space: O(1)O(1)

Last updated

Was this helpful?