LeetCode HOT100 - 字符串解码

感觉和括号或者计算式子比较像

因此用栈去模拟

每次碰到 ']' ,就处理好这个 '[' ']' 包裹的式子

处理好后仍然放到栈中,因为可能会被更大的 '[' ']' 包裹

整体就是模拟

class Solution {
public:
    string decodeString(string s) {
        vector<char> st;
        for (char c : s) {
            if (c != ']') {
                st.push_back(c);
            } else {
                string tmp;
                while (!st.empty() && st.back() != '[') {
                    tmp = st.back() + tmp;
                    st.pop_back();
                }
                st.pop_back();
                int num = 0, base = 1;
                while (!st.empty() && isdigit(st.back())) {
                    num += (st.back() - '0') * base;
                    base *= 10;
                    st.pop_back();
                }
                for (int i = 0; i < num; i++) {
                    for (char ch : tmp) {
                        st.push_back(ch);
                    }
                }
            }
        }
        return string(st.begin(), st.end());
    }
};
posted @ 2026-03-29 22:32  rdcamelot  阅读(14)  评论(0)    收藏  举报