Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-12-03 16:13:20
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字串一個一個加 好笨

Links booklink

Contact Us: admin [ a t ] ucptt.com