码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String

时间:2014-12-03 12:25:23      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        arr = s.split( )
        l = len(arr)
        ans = ""
        i = l-1
        while i>=0 and arr[i]==‘‘ :
            i=i-1
        j = 0
        while j<l and arr[j]==‘‘:
            j += 1
        if i>=j:
            ans = arr[i]
            i = i-1
        while i>=j :
            if arr[i]!=‘‘:
                ans = ans + " " + arr[i]
            i=i-1
        return ans

 

Reverse Words in a String

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/code-swan/p/4139566.html

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