Description:
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 3:
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.
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up:
For C programmers, try to solve it in-place in O(1) extra space.
Solutions:
NOTE: 直接调用Python的split函数是不行的,无法分割多个space的情况
class Solution:
def reverseWords(self, string: str) -> str:
words = []
cache = ""
string += " "
for s in string:
if s != " ":
cache += s
elif cache:
words.append(cache)
cache = ""
return " ".join(words[::-1])
Runtime: 44 ms, faster than 30.69% of Python3 online submissions for Reverse Words in a String.
Memory Usage: 14.5 MB, less than 5.05% of Python3 online submissions for Reverse Words in a String.
sample 32 ms submission
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(reversed(s.strip().split()))
https://stackoverflow.com/questions/13783934/what-does-s-strip-do-exactly
You should perhaps check out the docs for the function. It trims leading and trailing whitespace.
" ss ss ".strip()
becomes"ss ss"
Relevant link: http://docs.python.org/2/library/stdtypes.html#str.strip
Additionally, there is a very powerful tool within the Python interactive interpreter - you can do something like
help("".strip)
to get a bevy of useful information.