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 分钟前
Redis核心数据结构
数据结构·数据库·redis
Physicist in Geophy.5 分钟前
一维波动方程(从变分法角度)
线性代数·算法·机器学习
晴殇i6 分钟前
【前端缓存】localStorage 是同步还是异步的?为什么?
前端·面试
im_AMBER12 分钟前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
Liue6123123113 分钟前
【YOLO11】基于C2CGA算法的金属零件涂胶缺陷检测与分类
人工智能·算法·分类
数智工坊14 分钟前
【数据结构-树与二叉树】4.7 哈夫曼树
数据结构
!!!!81317 分钟前
蓝桥备赛Day1
数据结构·算法
Mr_Xuhhh18 分钟前
介绍一下ref
开发语言·c++·算法
七点半77018 分钟前
linux应用编程部分
数据结构
王老师青少年编程20 分钟前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(完善程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组