LeetCode 557. 反转字符串中的单词 III

2022-09-01  本文已影响0人  草莓桃子酪酪
题目

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

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

方法
class Solution(object):
    def reverseWords(self, s):
        result, word = [], []
        i, length = 0, len(s)
        while i <= length:
            if i < length and s[i] != ' ':
                word.append(s[i])
            else:
                left, right = 0, len(word)-1
                while left < right:
                    word[left], word[right] = word[right], word[left]
                    left += 1
                    right -= 1
                result.append(''.join(word))
                word = []
            i += 1
        return ' '.join(result)
上一篇 下一篇

猜你喜欢

热点阅读