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;
    }
}; 
相关推荐
海石5 分钟前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石6 分钟前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
aaPIXa62215 分钟前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
Augustzero37 分钟前
`co_await` 按下暂停键之后:从零看懂 C++20 协程
c++·后端
码少女43 分钟前
数据结构——希尔排序
数据结构·排序算法
知无不研1 小时前
c语言和c++中的静态关键字
开发语言·c++·静态关键字
星子yu1 小时前
【学习】怎么学好数据结构
数据结构·学习
2601_949818092 小时前
Vector从入门到应用(C++ STL动态数组万字全解
开发语言·c++
汉克老师2 小时前
GESP2026年6月认证C++八级( 第三部分编程题(1、线网建设))精讲
c++·最小生成树·排序·kruskal·并查集·gesp8级
胖大和尚2 小时前
Linux 内核工程师、HPC工程师、C++工程师
c++·kernel·hpc