题目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
代码:oj在线测试通过 Runtime: 172 ms
1 class Solution: 2 # @param s, a string 3 # @return a string 4 def reverseWords(self, s): 5 words = s.split(‘ ‘) 6 7 if len(words) < 2 : 8 return s 9 10 tmp = "" 11 for word in words: 12 word = word.replace(‘ ‘,‘‘) 13 if word != "" : 14 tmp = word + " " + tmp 15 16 tmp = tmp.strip() 17 18 return tmp
思路:
把中间多个空格考虑去除了就OK了
最后用strip()函数把首位的空白去了
时间: 2024-10-13 01:24:29