557. Reverse Words in a String III

原题网址:https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
大意:将一个英文句子按照空格分割成单次,每个单次反写。
比如:

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

split()方法分割后再反写就行了,反写方法[::-1]对list,string都有用。

def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        list = s.split(' ')
        for n,item in enumerate(list):
            list[n] = ''.join(item[::-1])
        return ' '.join(list)

再简化一下,用上循环表达式

def reverseWords2(self, s):
        """
        :type s: str
        :rtype: str
        """
        tmp = s.split()
        return ' '.join(i[::-1] for i in tmp)

知识点:

  1. [::-1]的反写方法
  2. 尽量用循环表达式来简化代码。



所有题目解题方法和答案代码地址:https://github.com/fredfeng0326/LeetCode

你可能感兴趣的:(557. Reverse Words in a String III)