1 条题解

  • 0
    @ 2026-2-25 11:59:32

    这道题的核心是处理嵌套压缩,用递归是最直接的方法:

    1. 用一个全局索引 i 记录当前处理到字符串的位置。
    2. 写一个递归函数,返回从当前位置开始直到遇到 ](或结束)时解压缩的子串:
      • 遇到普通字母,直接加入结果,索引 i 后移。
      • 遇到 [:先跳过 [ 读取数字 D(1-2位),再递归得到括号内子串 X,最后跳过 ],将 X 重复 D 次加入结果。
    3. 主函数启动递归,输出最终结果即可。

    代码

    #include <iostream>
    #include <string>
    #include <cctype>
    using namespace std;
    
    string s;
    int i;
    
    string dfs() {
        string tmp;
        while (i < s.size() && s[i] != ']') {
            if (s[i] == '[') {
                i++;
                int d = 0;
                while (isdigit(s[i])) {
                    d = d * 10 + s[i] - '0';
                    i++;
                }
                string t = dfs();
                i++;
                for (int j = 0; j < d; j++)
                    tmp += t;
            } else {
                tmp += s[i];
                i++;
            }
        }
        return tmp;
    }
    
    int main() {
        cin >> s;
        i = 0;
        cout << dfs() << endl;
        return 0;
    }
    
    • 1

    信息

    ID
    876
    时间
    1000ms
    内存
    512MiB
    难度
    5
    标签
    递交数
    19
    已通过
    6
    上传者