LeetCode OJ 系列之151 Reverse Words in a String --Python

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ln152315/article/details/50229581

Problem:

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

Answer:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        
        tmp = s.split()
        if len(tmp) == 0: return ""
        results = tmp[-1]
        for i in range(len(tmp)-2,-1,-1):
            results += " "+tmp[i]
        return results

猜你喜欢

转载自blog.csdn.net/ln152315/article/details/50229581