日野弥生:勉強しよう
LeetCode LCR 181 - 字符串中的单词反转
发表于2025年04月17日
双指针法,在前后指针之间完成翻转。
class Solution:
def reverseMessage(self, message: str) -> str:
# 先调用split()分割后再用单一空格进行字符串组合,倒序输出到列表中方便遍历
strLst = list(' '.join(message.split())[::-1])
sLen = len(strLst)
head, tail = 0, sLen - 1
# 去除前导空格(实际上可能不需要做)
while head < sLen and strLst[head] == ' ':
head += 1
while tail >= 0 and strLst[tail] == ' ':
tail -= 1
first, second = head, head
while first <= tail and second <= tail:
# 利用内层循环直接让tail冲到能进行交换的地方,避免tail出了外循环后还要最后在循环外再做一次反转
while second <= tail and strLst[second] != ' ':
second += 1
# 用切片法反转最优雅
strLst[first:second] = strLst[first:second][::-1]
first = second + 1
second += 1
return "".join(strLst)