首页 > 代码库 > Reverse Words in a String

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

 

Reverse Words in a String