// 演算法：純模擬。用 std::string 當作會自動長大的緩衝區，逐字處理 s：
//        字母 push_back、'*' pop_back、'#' 自我串接加倍、'%' 用 std::reverse 反轉。
// Algorithm: pure simulation with std::string as a growable buffer; per char:
//        letter -> push_back, '*' -> pop_back, '#' -> append self, '%' -> std::reverse.

#include <string>      // std::string
#include <algorithm>   // std::reverse

class Solution {
public:
    std::string processStr(std::string s) {
        std::string result;                       // 自動長大的字元容器 / auto-growing char container

        for (char c : s) {                        // range-for：依序取出 s 的每個字元 / iterate each char of s
            if (c == '*') {                       // 刪除最後一個字元 / remove last char
                if (!result.empty())              // 只有非空時才能 pop / only when not empty
                    result.pop_back();            // pop_back 移除尾端字元 / removes the trailing char
            } else if (c == '#') {                // 複製自己接在後面 / duplicate result
                result += result;                 // string + string 串接：等同接上一份自己 / append a copy of itself
            } else if (c == '%') {                // 反轉整個 result / reverse the whole result
                // std::reverse(begin, end)：就地反轉這段區間 / reverses the range in place
                std::reverse(result.begin(), result.end());
            } else {                              // 否則是小寫字母 / otherwise a lowercase letter
                result.push_back(c);              // push_back 在尾端加一個字元 / append one char
            }
        }

        return result;                            // 回傳最終字串 / return the final string
    }
};
