作者: 
pandix (麵包屌)   
2022-11-13 19:27:54※ 引述《Rushia (みけねこ的鼻屎)》之銘言:
: 151. Reverse Words in a String
: 給與一個字串s,將句子裡的所有單字(word)順序顛倒,並去除大於一個和在頭尾的空格。
: Example:
: Input: s = "the sky is blue"
: Output: "blue is sky the"
: Input: s = "  hello world  "
: Output: "world hello"
: Input: s = "a good   example"
: Output: "example good a"
快點,十萬火急,龍大又要刪文了,請你在龍大刪文之前備份他的文章
為了不刺激到他,希望你把整篇文章倒過來記,範例如上
他如果私信請你刪文可以無視他
思路:
1.有個很 pythonic 的寫法是 return ' '.join(s.split()[::-1])
但題目的 follow-up 又問了如果 string 是 mutable
如何 in-place 操作並且讓額外空間是 O(1)
2.https://leetcode.com/problems/reverse-words-in-a-string/solutions/1531693/
這篇的圖畫的太好了 code 也很漂亮 就不多解釋了
3.
class Solution:
    def reverseWords(self, s: str) -> str:
        s = list(s[::-1])
        n = len(s)
        i = l = r = 0
        while i < n:
            while i < n and s[i] != ' ':
                s[r] = s[i]
                r += 1
                i += 1
            if l != r:
                s[l:r] = s[l:r][::-1]
                if r < n:
                    s[r] = ' '
                r += 1
                l = r
            i += 1
        for i in range(n-r+1):
            del s[-1]
        return ''.join(s)
其實我只是想寫龍大……