leetcode笔记--Reverse Words in a String

题目:难度(Medium)

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.

Clarification(声明):
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces(前缀空格或者后缀空格)?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Subscribe to see which companies asked this question
Tags:String
Similar Problems:(M) Reverse Words in a String II

分析:1.不含空白符的连续串组成一个单词
            2.颠倒后的字符串两侧不要有空白符,即使原串有
            3.单词之间如果有多个空格,只留下一个

代码实现:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        tmp = s.split()
        #原地反转
        tmp.reverse()
        return " ".join(tmp)
上面利用了python的很多内建函数,感觉有种作弊的嫌疑,下面自己老老实实的实现了一下:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        result = []
        tmpStr = ""
        for ch in s:
            if ch != " ":
                tmpStr += ch
            else:
                if tmpStr != "":
                    result.append(tmpStr)
                    tmpStr = ""
        if tmpStr != "":
            result.append(tmpStr)
        #原地反转
        result.reverse()
        return " ".join(result)

你可能感兴趣的:(LeetCode,python,String)