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;
    }
}; 
相关推荐
晚风叙码1 分钟前
从0吃透C++入门|第一个程序、命名空间与缺省函数基础
开发语言·c++
搬砖魁首2 分钟前
基础能力系列 - 多线程1 - 内存序
算法·内存序·memory order
j_xxx404_3 分钟前
Linux线程:核心机制与优雅的 C++ 封装实践|附源码
linux·运维·服务器·开发语言·c++·人工智能·ai
W23035765736 分钟前
手写 muduo 库:基于 Reactor 模型打造高性能网络通信框架
c++·reactor·tcp·muduo库
pursuit_csdn7 分钟前
力扣周赛 503
java·算法·leetcode
Zhang~Ling10 分钟前
C++ 模板进阶:非类型参数、特化与分离编译深度解析
开发语言·c++
sheeta199813 分钟前
LeetCode 每日一题笔记 日期:2026.05.21 题目:3043. 最长公共前缀的长度
笔记·算法·leetcode
加油201914 分钟前
嵌入式软件技术栈和学习路线详解
linux·arm开发·数据结构·mqtt·设计模式·嵌入式
Oj92q85H514 分钟前
如何在Dev-C++中使用TDM-GCC编译项目
linux·开发语言·c++
吃好睡好便好16 分钟前
创建随机矩阵
开发语言·人工智能·线性代数·算法·matlab·矩阵