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;
    }
}; 
相关推荐
科技苑1 小时前
C++ CAS与ABA问题详解,无锁编程的经典陷阱怎么解决?
c++·人工智能
GoAI2 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi2 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
Zan3 小时前
SQLite + SQLx 实战:为什么已经发布的数据库迁移文件,绝对不能再修改?
数据库·后端·面试
我叫黑大帅4 小时前
PHP 常驻 Worker 中 MySQL 连接中断问题报告
后端·面试·php
choumou_M5 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen5 小时前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
BaiPeter5 小时前
ZPL文件预览
开发语言·c++
Moment6 小时前
代码都能让 Agent 写了,我们为什么还要学前端?
前端·后端·面试