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;
    }
}; 
相关推荐
地平线开发者4 分钟前
不同传感器前中后融合方案简介
算法·自动驾驶
Mr_WangAndy11 分钟前
C++_chapter15_C++重要知识点_lambda,initializer_list
c++·lambda·初始化列表
地平线开发者14 分钟前
征程 6X 常见 kernel panic 问题
算法·自动驾驶
Maple_land16 分钟前
第1篇:Linux工具复盘上篇:yum与vim
linux·运维·服务器·c++·centos
许强0xq32 分钟前
Q3: create 和 create2 有什么区别?
面试·web3·区块链·智能合约·solidity·dapp·evm
han_1 小时前
前端高频面试题之Vuex篇
前端·vue.js·面试
hggngx548h1 小时前
有哪些C++20特性可以在Dev-C++中使用?
开发语言·c++·c++20
com_4sapi1 小时前
2025 权威认证头部矩阵系统全景对比发布 双榜单交叉验证
大数据·c语言·人工智能·算法·矩阵·机器人
前端小L1 小时前
二分查找专题(九):“降维”的魔术!将二维矩阵“拉平”为一维
数据结构·算法
Jasmine_llq2 小时前
《P7516 [省选联考 2021 A/B 卷] 图函数》
算法·弗洛伊德算法·floydwarshall算法·后缀和计算