leetcode 【 Reverse Words in a String 】python 实现

时间:2014-12-27 01:25:36   收藏:0   阅读:531

题目

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()函数把首位的空白去了

原文:http://www.cnblogs.com/xbf9xbf/p/4187873.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!