[LeetCode&Python] Problem 557. Reverse Words in a String III

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode&Python] Problem 557. Reverse Words in a String III相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/tco' title='tco'>tco   tput   ace   leetcode   res   test   The   output   any   

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鈥榮 take LeetCode contest"
Output: "s鈥榯eL 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.

 

My first solution:

class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        answer=鈥樷€?        smallstr=鈥樷€?        
        for c in s:
            if c==鈥?鈥?
                smallstr=smallstr[::-1]
                answer=answer+smallstr+鈥?鈥?                smallstr=鈥樷€?            else:
                smallstr=smallstr+c
                
        return answer+smallstr[::-1

銆€銆€

A much shorter solution:

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

銆€銆€

以上是关于[LeetCode&Python] Problem 557. Reverse Words in a String III的主要内容,如果未能解决你的问题,请参考以下文章

C++&Python描述 LeetCode C++&Python描述 LeetCode 剑指 Offer 22. 链表中倒数第k个节点

[LeetCode&Python] Problem 202. Happy Number

[LeetCode&Python] Problem 520. Detect Capital

[LeetCode&Python] Problem 383. Ransom Note

[LeetCode&Python] Problem 458. Poor Pigs

[LeetCode&Python] Problem 682. Baseball Game