力扣 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;
    }
};
相关推荐
a187927218311 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_962297481 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye2 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展
辰烨chenye2 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
手写码匠2 小时前
华为云Flexus+DeepSeek征文|DeepSeek 应用监控告警体系实战:从“用户投诉才知道“到“故障前就发现“
人工智能·深度学习·算法·aigc
shehuiyuelaiyuehao3 小时前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
智购科技自动售货机厂家3 小时前
2026自动售货机设备清洁效果自动验证:从图像比对到评分算法的工程实践~YH
人工智能·算法·计算机视觉
姜穆澜3 小时前
机器学习实战指南:从算法原理到工程落地
人工智能·算法·机器学习
Q一件事4 小时前
RWEQ——保留与消去P的soil_loss联合推导
算法