2026年6月16日 星期二

LeetCode 解題筆記:3612. Process String with Special Operations I

作者:王一哲
日期:2026年6月16日


LeetCode 題目連結:3612. Process String with Special Operations I

解題想法


中等難度,標準的字串操作題。只要按照題目的要求處理字串即可,假設目前的內容儲存於 result,操作有以下 3 種:
  1. * 移除 result 最後一項
  2. # 複製 result 的所有內容
  3. % 將 result 反序
如果用 Python 解題,可以先將結果存到串列,最後再接成字串並回傳,也可以直接用字串儲存結果。在我以前解題的經驗中,用串列的速度比較快,但沒想到這題是直接用字串儲存結果速度比較快。如果用 C++ 解題就直接用字串儲存結果,因為 C++ 的字串可以用 pop_back() 移除最後一項,也可以用 reverse 直接反序,操作上很方便。

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
    }
};

沒有留言:

張貼留言