日期:2026年6月16日
LeetCode 題目連結:3612. Process String with Special Operations I
解題想法
中等難度,標準的字串操作題。只要按照題目的要求處理字串即可,假設目前的內容儲存於 result,操作有以下 3 種:
- * 移除 result 最後一項
- # 複製 result 的所有內容
- % 將 result 反序
Python 程式碼
Runtime: 23 ms, beats 69.08%. Memory: 25.92 MB, beats 44.08%.
class Solution:
def processStr(self, s: str) -> str:
arr = [] # 用串列儲存結果比較好操作
for c in s:
if c.isalpha(): # 字母,直接加到 arr 最後面
arr.append(c)
elif c == '*': # 移除 arr 最後一項
if arr: arr.pop()
elif c == '#': # 複製 arr 全部的內容
if arr: arr += arr
elif c == '%': # arr 倒序
arr.reverse()
return "".join(arr) # 組成字串再回傳
Runtime: 0 ms, beats 100.00%. Memory: 23.24 MB, beats 82.24%.
class Solution:
def processStr(self, s: str) -> str:
t = "" # 用字串儲存結果
for c in s:
if c.isalpha(): # 字母,直接加到 t 最後面
t += c
elif c == '*': # 移除 t 最後一項
if t: t = t[:-1]
elif c == '#': # 複製 t 全部的內容
if t: t += t
elif c == '%': # t 倒序
t = t[::-1]
return t # 回傳 t