top1编程
← 返回题目
题解

【基础】字符串解压

1 条题解

  • 0
    @ 2026-7-30 1:33:35

    解题思路

    先读取连续数字得到重复次数,再输出后面的字母;没有数字时次数为1。

    参考代码

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string s;
        cin >> s;
        for (int i = 0; i < (int)s.size();) {
            int n = 0;
            // 连续读取数字,组成重复次数。
            while (i < (int)s.size() && s[i] >= '0' && s[i] <= '9') {
                n = n * 10 + s[i] - '0';
                i++;
            }
            // 没有数字时,说明这个字母只出现一次。
            if (n == 0) n = 1;
            char c = s[i++];
            // 按次数把当前字母输出出来。
            for (int j = 1; j <= n; j++) cout << c;
        }
        return 0;
    }
    

    复杂度分析

    代码只使用了简单变量、循环和字符串。设输入长度为 n,时间复杂度为 O(n^2)(若有嵌套枚举则按实际循环计算),额外空间复杂度为 O(n)。

    • 1