力扣 394. 字符串解码

🔗 https://leetcode.cn/problems/decode-string

题目

  • 对字符串中的 ks 解码为 s 重复 k 次

思路

  • 碰到数字,开始进行递归 decode 展开,否则字符不解码
  • 针对于解码的部分,先明确 k 的数字是多少,再明确 括号中的 str 是什么,最后重复 k 次
  • 注意这个过程中,要是碰到字符串是数字开头,递归进行 decode

代码

cpp 复制代码
class Solution {
public:
    string decode(string s, int start, int& ori_len) {
        int index = start;
        int num = 0;
        while (s[index] != '[') {
            num = num* 10 +  s[index] - '0';
            index++;
        }

        string str;
        for (int i = index + 1; i < s.size(); i++) {
            if (s[i] == ']') {
                ori_len = i - start;
                break;
            }
            if (s[i] >= '0' && s[i] <= '9') {
                int len = 0;
                str += decode(s, i, len);
                i += len;
            } else {
                str += s[i];
            }
        }

        string ans;
        while (num--) {
            ans += str;
        }

        return ans;
    }
    string decodeString(string s) {
        string ans;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] >= '0' && s[i] <= '9') {
                int ori_len = 0;
                ans += decode(s, i, ori_len);
                i += ori_len;
            } else {
                ans += s[i];
            }
        }
        return ans;
    }
};
相关推荐
一只小小的芙厨1 小时前
【线性DP】
学习·算法·动态规划
奋发向前wcx1 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法
罗湖老棍子3 小时前
C Looooops(信息学奥赛一本通- P1640)
算法·数论·同余·裴蜀定理·扩展欧几里得
飘尘5 小时前
从"算子"到"AI Infra":大模型背后看不见的那群人在忙什么
人工智能·算法·面试
夏幻灵6 小时前
每日一题:LeetCode 3:无重复字符的最长子串——滑动窗口思路详解
算法·leetcode·职场和发展
CarIise6 小时前
Java实训阶段查漏补缺复习笔记2
java·linux·算法
无忧.芙桃7 小时前
C++ 并查集详解:原理、实现与应用
c语言·c++·算法·leetcode
蛋蛋的就会顺顺的7 小时前
hot100——二叉树
java·数据结构·算法·leetcode·力扣
Code_Solitude7 小时前
c语言:二分法的完整补充
c语言·开发语言·算法
一切皆是因缘际会7 小时前
掌控信息论:同源星际通信基础理论
人工智能·算法·ai