Leetcode 557. Reverse Words in a String III

时间:2022-12-22 15:48:29
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()])