Leetcode 151. Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
思路很简单,注意使用s.split()而不是s.split(" ")。如果两个单词中间有多于一个空格,或者 s = ' ' 这种情况,split()不加任何参数可以处理这种多于一个空格的情况。
1 class Solution(object): 2 def reverseWords(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 8 words = s.split() 9 # words = words[::-1] 10 words.reverse() 11 return " ".join(words)