Leetcode 577

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 

注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

方法一: 效率稍微有点低,不过在可以接受的范围内

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

方法二: 充分利用字符串的方法, 博主对这个不是特别熟悉,也算学习了

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

猜你喜欢

转载自blog.csdn.net/jhlovetll/article/details/84110414
今日推荐