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;
    }
}; 
相关推荐
Hi李耶4 分钟前
【LeetCode】9-回文数
算法·leetcode·职场和发展
红叶舞5 分钟前
基于线段树的数据结构
数据结构·python·算法
断点之下1 小时前
从“理扑克牌”到“分组优化”——直接插入排序与希尔排序详解
数据结构·算法·排序算法
起个破名想半天了1 小时前
算法与数据结构之DFS深度优先遍历
数据结构·算法·深度优先
李伟_Li慢慢1 小时前
凸包算法
人工智能·算法
徐礼昭|商派软件市场负责人1 小时前
AI Agent 蜂群协作与经验基因化:从单体执行到自组织系统的工程路径
大数据·人工智能·算法·智能体·多agent
来者皆善1 小时前
【位RAW图像处理五】任意位深位图像的中值模糊快速实现及其应用。
图像处理·人工智能·算法
计算机内卷的N天1 小时前
CMake与Visual Studio的使用
c++·ide·visual studio
happyprince1 小时前
第三观 · 深刻不忘观 —— AngelSpec 哲学与升华
人工智能·算法
汉克老师1 小时前
GESP2026年3月认证C++七级( 第三部分编程题(1、物流网络))精讲
c++·最短路·gesp7级