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;
    }
}; 
相关推荐
John_ToDebug16 小时前
Chromium 源码剖析:base::NoDestructor——更安全的静态单例解决方案
开发语言·c++·chrome
llm大模型算法工程师weng16 小时前
Java面试核心突破:面向对象与设计模式
java·设计模式·面试
星马梦缘16 小时前
离散数学——图论 作战记录
算法·深度优先·图论·离散数学·生成树·哈密顿图·欧拉图
tankeven16 小时前
C++ 学习杂记02:C++模板编程
c++
m0_7431064616 小时前
【浙大&南洋理工最新综述】Feed-Forward 3D Scene Modeling(四)
深度学习·算法·计算机视觉·3d·几何学
Peregrine916 小时前
数据结构 - > 双链表
c语言·数据结构·算法
计算机安禾16 小时前
【Linux从入门到精通】第9篇:用户与权限管理(下)——数字法与粘滞位
linux·服务器·人工智能·面试·知识图谱
楼田莉子16 小时前
仿muduo的高并发服务器——前置知识讲解和时间轮模块
服务器·开发语言·c++·后端·学习
小江的记录本16 小时前
【分布式】分布式核心组件——分布式限流:固定窗口、滑动窗口、漏桶、令牌桶算法,网关层/服务层限流实现
java·分布式·后端·python·算法·安全·面试
OYangxf16 小时前
C++中的回调函数:从函数指针到现代可调用对象
c++