日期: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
C++ 程式碼
Runtime: 4 ms, beats 63.64%. Memory: 39.63 MB, beats 87.50%.
class Solution {
public:
string processStr(string s) {
string t; // 用字串儲存結果
for(char c : s) {
if (isalpha(c)) { // 字母,直接加到 t 最後面
t += c;
} else if (c == '*') { // 移除 t 最後一項
if (!t.empty()) t.pop_back();
} else if (c == '#') { // 複製 t 全部的內容
if (!t.empty()) t += t;
} else if (c == '%') { // t 倒序
reverse(t.begin(), t.end());
}
}
return t; // 回傳 t
}
};
沒有留言:
張貼留言