LeetCode75——Day26

文章目录

一、题目

394. Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_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 2[4].

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

Example 1:

Input: s = "3[a]2[bc]"

Output: "aaabcbc"

Example 2:

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

Output: "accaccacc"

Example 3:

Input: s = "2[abc]3[cd]ef"

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 小时前
C++ 面向对象
c++
Hilaku5 小时前
Token已过期,我是如何实现无感刷新Token的?
前端·javascript·面试
Mor_5 小时前
UE5核心宏标记 (UCLASS, UPROPERTY, UFUNCTION) 学习笔记
面试
CoovallyAIHub5 小时前
中科大DSAI Lab团队多篇论文入选ICCV 2025,推动三维视觉与泛化感知技术突破
深度学习·算法·计算机视觉
沐怡旸5 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
Java中文社群6 小时前
有点意思!Java8后最有用新特性排行榜!
java·后端·面试
moisture6 小时前
CUDA常规知识点
后端·面试
NAGNIP6 小时前
Serverless 架构下的大模型框架落地实践
算法·架构
zcychong6 小时前
ArrayMap、SparseArray和HashMap有什么区别?该如何选择?
android·面试
moonlifesudo6 小时前
半开区间和开区间的两个二分模版
算法