力扣 394. 字符串解码

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

题目

  • 对字符串中的 k[s] 解码为 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;
    }
};
相关推荐
秋说9 分钟前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
qq_5139704421 分钟前
力扣 hot100 Day37
算法·leetcode
不見星空41 分钟前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack1 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
DoraBigHead2 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx3 小时前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior3 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者3 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7894 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价4 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae