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)
Test case 2 (with spaces at the beginning and the end)
Test case 3 (only spaces in the string)
Test case 4 (empty string)
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
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
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
Last updated