【394.字符串解码】

目录

一、题目描述

二、算法原理

三、代码实现

cpp 复制代码
class Solution {
public:
    string decodeString(string s) 
    {
        stack<string> s1;
        s1.push("");
        stack<int> s2;
        int i = 0, n = s.size();
        while (i < n)
        {
            //1.如果是数字入数字栈
            if (s[i] >= '0' && s[i] <= '9')
            {
                int sum = 0;
                while (s[i] >= '0' && s[i] <= '9')
                {
                    int val = s[i] - '0';
                    sum = sum * 10 + val;
                    i++;
                }
                s2.push(sum);
            }

            //2.如果是[ 统计后面的字符串入字符串栈
            else if (s[i] == '[')
            {
                string str;
                i++;
                while (s[i] >= 'a' && s[i] <= 'z') str += s[i++];
                s1.push(str);
            }

            //3.如果是] 解码后入字符栈顶的子串后面
            else if (s[i] == ']')
            {
                int times = s2.top();
                s2.pop();
                string temp = s1.top();
                s1.pop();
                while (times--) s1.top() += temp;
                i++;
            }

            //4.如果是字符 把字符串入栈顶的子串后面
            else if (s[i] >= 'a' && s[i] <= 'z')
            {
                string str;
                while (s[i] >= 'a' && s[i] <= 'z') str += s[i++];
                if (str.size() > 0) s1.top() += str;
            }
        }
        return s1.top();
   
        
    }
};
相关推荐
05Kevin7 小时前
lk每日冒险题--数据结构6.27
算法
To_OC18 小时前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安1 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者1 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
卷无止境1 天前
C++ 的Eigen 库全解析
c++
卷无止境1 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴1 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake