Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (麵包屌)時間3年前 (2022/11/13 19:27), 編輯推噓1(102)
留言3則, 3人參與, 3年前最新討論串100/719 (看更多)
※ 引述《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) 其實我只是想寫龍大…… -- 蛤? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.212.49 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1668338879.A.4E6.html

11/13 19:28, 3年前 , 1F
大師
11/13 19:28, 1F

11/13 19:43, 3年前 , 2F
大師
11/13 19:43, 2F

11/13 19:46, 3年前 , 3F
笑了
11/13 19:46, 3F
文章代碼(AID): #1ZSDI_Jc (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZSDI_Jc (Marginalman)