难度:简单
知识点:字符串
地址:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
from typing import *
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
t = s[i]
s[i] = s[j]
s[j] = t
i += 1
j -= 1
def reverseWords(self, s: str) -> str:
words = s.split(" ")
new_words = []
for w in words:
ws = w.split("")
self.reverseString(ws)
new_words.append(''.join(ws))
return ' '.join(new_words)
s = Solution()
s.reverseWords("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc"