Leetcode 557. Reverse Words in a String III

class Solution:
    def reverseWords(self, s: str) -> str:
        s = s.split()
        ans = ''
        for i in s:
            ans += ''.join(list(reversed(i))) + ' '
        return ans.strip()

优化:字符串的反转可以用切片来完成:string[::-1]

class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join([word[::-1] for word in s.split()])

 

posted @ 2019-04-21 04:26  周洋  阅读(130)  评论(0编辑  收藏  举报