您的位置:首页 > 编程语言 > Python开发

leetcode 【 Reverse Words in a String 】python 实现

2014-12-27 00:12 525 查看
题目

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

class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
words = s.split(' ')

if len(words) < 2 :
return s

tmp = ""
for word in words:
word = word.replace(' ','')
if word != "" :
tmp = word + " " + tmp

tmp = tmp.strip()

return tmp


思路

把中间多个空格考虑去除了就OK了

最后用strip()函数把首位的空白去了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: