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;
    }
}; 
相关推荐
Hcoco_me17 小时前
大模型面试题17:PCA算法详解及入门实操
算法
跨境卫士苏苏17 小时前
亚马逊AI广告革命:告别“猜心”,迎接“共创”时代
大数据·人工智能·算法·亚马逊·防关联
ZouZou老师17 小时前
C++设计模式之装饰器模式:以家具生产为例
c++·设计模式·装饰器模式
ZouZou老师17 小时前
C++设计模式之桥接模式:以家具生产为例
c++·设计模式·桥接模式
程序员小白条17 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
呱呱巨基17 小时前
Linux 进程概念
linux·c++·笔记·学习
liulilittle17 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
云雾J视界17 小时前
当算法试图解决一切:技术解决方案主义的诱惑与陷阱
算法·google·bert·transformer·attention·算法治理
Xの哲學17 小时前
Linux Miscdevice深度剖析:从原理到实战的完整指南
linux·服务器·算法·架构·边缘计算
无责任此方_修行中17 小时前
亲历外企裁员:上午还在写代码,下午工位就空了
面试·程序员·求职