Re: [閒聊] 每日leetcode
看板Marginalman作者JerryChungYC (JerryChung)時間1年前 (2024/12/03 16:13)推噓0(0推 0噓 0→)留言0則, 0人參與討論串1175/1548 (看更多)
https://leetcode.com/problems/adding-spaces-to-a-string
2109. Adding Spaces to a String
在指定index插空格
Example 1:
Input: s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]
Output: "Leetcode Helps Me Learn"
Example 2:
Input: s = "icodeinpython", spaces = [1,5,7,9]
Output: "i code in py thon"
Example 3:
Input: s = "spacing", spaces = [0,1,2,3,4,5,6]
Output: " s p a c i n g"
Constraints:
1 <= s.length <= 3 * 10^5
s 只有大小寫英文字母
1 <= spaces.length <= 3 * 10^5
0 <= spaces[i] <= s.length - 1
spaces內的值是嚴格遞增
思路:
根據spaces把範圍內的字串加到list內 最後用空格串起來
最後一組字串也要記得加
Python Code:
class Solution:
def addSpaces(self, s: str, spaces: List[int]) -> str:
ans = []
i = 0
for space in spaces:
ans.append(s[i:space])
i = space
ans.append(s[i:])
return ' '.join(ans)
一開始還在for字串一個一個加 好笨
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.25.235 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1733213603.A.B5A.html
※ 編輯: JerryChungYC (114.45.25.235 臺灣), 12/03/2024 16:15:00
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1175 之 1548 篇):