码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 【 Reverse Words in a String 】python 实现

时间:2014-12-27 01:26:47      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

题目

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

leetcode 【 Reverse Words in a String 】python 实现

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!