力扣 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;
    }
};
相关推荐
叁散12 小时前
ESP32 LCD1602显示实验报告
算法
过期动态12 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒12 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
君为先-bey12 小时前
LeMiCa——基于扩散模型的高效视频生成的词典序最小化路径缓存
python·算法·机器学习·扩散模型
洛水水12 小时前
【力扣100题】58.轮转数组
算法·leetcode
资深流水灯工程师12 小时前
LMS 最小均方算法在 DSP 上的 C 语言实现
算法
风筝在晴天搁浅12 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-13 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
05候补工程师13 小时前
【408考研·数据结构专题】二叉树、树与森林、线索树及哈夫曼树核心考点与秒杀技巧深度总结
数据结构·经验分享·笔记·考研·算法
吃好睡好便好13 小时前
矩阵的加减运算
开发语言·人工智能·学习·线性代数·算法·matlab·矩阵