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

151. Reverse Words in a String Leetcode Python

时间:2015-03-30 09:24:11      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:string   leetcode   python   

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.

linear time:

1. go through the string detect whether the place is  ‘  ‘ if not append the char to word

2 if the place is  ‘  ‘ and word is not "" append the word to res

3. go to the end append the word if the word is not ""

reverse the res


4. do join.

class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        i = 0
        res = []
        word = ''
        while i < len(s):
            if s[i] != ' ':
                word += s[i]
            elif s[i] == ' ' or i == len(s) - 1:
                if word != "":
                    res.append(word)
                word = ""
            i += 1
        if word != "":
            res.append(word)
        res.reverse()
        return " ".join(res)


151. Reverse Words in a String Leetcode Python

标签:string   leetcode   python   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/44733781

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