Leetcode练习(python):字符串类:第151题:翻转字符串里的单词:给定一个字符串,逐个翻转字符串中的每个单词。

题目:
翻转字符串里的单词:给定一个字符串,逐个翻转字符串中的每个单词。

说明:

无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

思路:

思路较简单。

程序:

class Solution:
    def reverseWords(self, s: str) -> str:
        s = s.strip()
        length = len(s)
        index = length - 1
        anchor = length
        result = []
        while index >= 0:
            while index >= 0 and s[index] != ' ':
                index -= 1
            result.append(s[index + 1 : anchor])
            while s[index] == ' ':
                index -= 1
            anchor = index + 1
        return ' '.join(result)
原文地址:https://www.cnblogs.com/zhuozige/p/12843504.html