Reverse Words in a String

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

 

posted on 2014-12-03 11:26  code#swan  阅读(76)  评论(0)    收藏  举报

导航