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;
    }
}; 
相关推荐
极客BIM工作室10 分钟前
OCCT gp_Trsf 三维变换类深度剖析:经典设计与底层陷阱
c++
code_pgf12 分钟前
改进模型架构来减少MLLMs中的幻觉现象
人工智能·深度学习·算法
2301_7644413319 分钟前
基于AI的本地文件归档智能管理工具梳理
人工智能·python·算法·目标检测·交互
醉城夜风~23 分钟前
类和对象III
开发语言·c++
无限码力25 分钟前
美团研发岗 4月18号笔试真题 - 包包的最长公共子序列3
算法·美团笔试题·美团研发岗笔试题·美团机试题
怪兽学LLM41 分钟前
LeetCode 21 合并两个有序链表:彻底理解虚拟头节点(Dummy)套路
python·leetcode·链表
阿里matlab建模师42 分钟前
基于matlab时域频域处理的语音信号变声处理系统设计与算法原理(论文+程序源码+GUI图形用户界面)——变声算法
算法·matlab·语音识别
IMPYLH1 小时前
HTML 的 <abbr> 元素
前端·算法·html
leo__5201 小时前
小波特征与模糊支持向量机(FSVM)的脑电信号分类方法
算法·支持向量机·分类
wabs6661 小时前
关于动态规划【纯粹的0-1背包需要思考的问题】
算法·动态规划