LeetCode75——Day26

文章目录

一、题目

394. Decode String

Given an encoded string, return its decoded string.

The encoding rule is: kencoded_string, where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 24.

The test cases are generated so that the length of the output will never exceed 105.

Example 1:

Input: s = "3a2bc"

Output: "aaabcbc"

Example 2:

Input: s = "3a2\[c]"

Output: "accaccacc"

Example 3:

Input: s = "2abc3cdef"

Output: "abcabccdcdcdef"

Constraints:

1 <= s.length <= 30

s consists of lowercase English letters, digits, and square brackets '\[\]'.

s is guaranteed to be a valid input.

All the integers in s are in the range 1, 300.

二、题解

cpp 复制代码
class Solution {
public:
    string decodeString(string s) {
        string ans;
        stack<pair<int, int>> stk;
        int count = 0;
        for (auto x : s) {
            if (isdigit(x)) 
                count = 10 * count + (x - '0');
            else if (x == '[') {
                stk.push({count, ans.size()});
                count = 0;
            }
            else if (isalpha(x)) 
                ans += x;
            else if (x == ']') {
                int n = stk.top().first;
                string str = ans.substr(stk.top().second, ans.size() - stk.top().second);
                for (int i = 0; i < n - 1; i++) {
                    ans += str;
                }
                stk.pop();
            }
        }
        return ans;
    }
}; 
相关推荐
电科_银尘4 分钟前
【大模型算法与工程 48】项目实战:可调用、可追踪的大模型问答服务
算法
电科_银尘26 分钟前
【大模型算法与工程 47】服务工程:并发、排队、限流与可观测性
算法
西数科技CDRSA1 小时前
BGA封装NAND芯片不识别,Flash Extractor引脚直读还原原始镜像
数据结构·算法·硬件工程
星恒随风1 小时前
C++11 加餐(2)并发支持库——mutex、lock_guard、unique_lock 与死锁问题
开发语言·c++
AvocadoZeroOneOI2 小时前
Kadane 算法(最大子段和)
c++·学习·算法·动态规划
汉克老师4 小时前
GESP六级第二课:森林里的分叉城堡——二叉树的构造与存储
c++·二叉树·树·gesp·小学生·小学生学编程
Lazyafei5 小时前
滑动窗口:扩张与收缩的动态区间
算法
FRing035 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
老歌老听老掉牙6 小时前
三个等价答案:遗传算法如何逼近 Branin 函数
c++·算法·ga
是main不是漫6 小时前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法