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;
    }
}; 
相关推荐
YouRock几秒前
面试必问HTTP状态码:从“请求的一生”彻底搞懂,告别死记硬背
面试
_OP_CHEN1 分钟前
【算法基础篇】(六十一)SG 函数通关指南:博弈论通用解法,从原理到实战秒杀各类 ICG 游戏
算法·蓝桥杯·c/c++·博弈论·acm/icpc·sg函数·有向图游戏
We་ct2 分钟前
LeetCode 2. 两数相加:链表经典应用题详解
前端·算法·leetcode·链表·typescript
If using 10 days9 分钟前
multiprocessing:创建并管理多个进程
python·算法
会周易的程序员9 分钟前
openplc runtime v4 安全
网络·c++·物联网·websocket·安全·https·ssl
wu_asia11 分钟前
每日一练壹
算法
程序员酥皮蛋14 分钟前
hot 100 第二十二题 22.相交链表
数据结构·算法·leetcode·链表
maplewen.16 分钟前
C++ 内存对齐
开发语言·c++
柒儿吖21 分钟前
三方库 Boost.Regex 在 OpenHarmony 的 lycium完整实践
c++·c#·openharmony
一只小小的芙厨27 分钟前
寒假集训·子集枚举2
c++·笔记·算法·动态规划