【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();
   
        
    }
};
相关推荐
曦樂~5 小时前
Cpp面筋
c语言·c++
道尔柯南5 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
Dream it possible!8 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊8 小时前
算法之双指针系列(一)
算法·leetcode
十二8 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
小此方9 小时前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
Pniubi10 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH10 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi11 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
zjxtxdy12 小时前
C++面向对象程序开发-类与对象
开发语言·c++