[LeetCode]题解(python):151-Reverse Words in a String

题目来源:

  https://leetcode.com/problems/reverse-words-in-a-string/


 

题意分析:

  给定一个字符串,里面包括多个单词,将这个字符串的单词翻转,例如"the sky is blue",得到"blue is sky the".


 

题目思路:

  首先获取每个单词,将单词记录到一个数组里面,然后翻转过来就行了。要处理的是前面和后面有空格的情况。


 

代码(python):

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s) == 0:
            return ""
        ans = []
        begin = i = 0
        mark = True
        while i < len(s):
            if s[i] != ' 'and mark:
                begin = i
                mark = False
            if s[i] == ' ' and i > 0 and s[i - 1] != ' ':
                ans.append(s[begin:i])
                while i < len(s) and s[i] == ' ':
                    i += 1
                begin = i
            i += 1
        if s[-1] != ' ':
            ans.append(s[begin:len(s)])
        #print(ans)
        j = len(ans)
        if j == 0:
            return ""
        res = ans[j - 1]
        j -= 1
        while j > 0:
            res += ' ' + ans[j - 1]
            j -= 1
        return res
View Code

 

  

posted @ 2016-05-10 16:20  Ry_Chen  阅读(451)  评论(0编辑  收藏  举报