首页 > 编程语言 > 详细

151. Reverse Words in a String Leetcode Python

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!