码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-05-10 16:42:05      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

  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

 

  

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

标签:

原文地址:http://www.cnblogs.com/chruny/p/5478262.html

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