[LeetCode]Reverse Words in a String III

题目描述:

LeetCode 557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

题目大意:

给定字符串,将每个单词逐字符逆置,返回新字符串。

注意:字符串中单词之间有且只有1个空格分开。

解题思路:

字符串处理

Python代码:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        return ' '.join(w[::-1] for w in s.split())

不使用split与内置函数逆置的解法

Python代码:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        clist, size = list(s), len(s)
        p = q = 0
        while p < size:
            while q < size and s[q] != ' ': q += 1
            for x in range((q - p) / 2):
                clist[p + x], clist[q - x - 1] = clist[q - x - 1], clist[p + x]
            p = q = q + 1
        return ''.join(clist)

 

本文链接:http://bookshadow.com/weblog/2017/04/09/leetcode-reverse-words-in-a-string-iii/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论