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;
    }
}; 
相关推荐
Sam092710 分钟前
【AI 算法精讲 13】朴素贝叶斯:文本分类的基石
人工智能·python·算法·ai
SilentSamsara13 分钟前
模型可解释性业务化:SHAP/LIME 的业务汇报与合规审查
人工智能·算法·机器学习·自动化
byte轻骑兵20 分钟前
【LE Audio】CSIP精讲[5]: 蓝牙协同设备组的安全防护体系与实战规范
算法·安全·音频·le audio·低功耗音频
剑挑星河月22 分钟前
35.搜索插入位置
java·数据结构·算法·leetcode
Huangjin007_28 分钟前
【C++11篇(二)】右值引用、移动语义保姆级讲解!
开发语言·c++
闪电悠米32 分钟前
力扣hot100-438.找到字符串中所有字母异位词-固定长度滑动窗口详解
linux·服务器·数据结构·算法·leetcode·滑动窗口·力扣hot100
人道领域39 分钟前
【LeetCode刷题日记】51.N皇后
数据结构·算法
芝士爱知识a9 小时前
AI 模拟面试怎么做:智蛙公考智能体多轮对话 + 实时追问的工程实现
面试·职场和发展
古城小栈9 小时前
为啥说:训练用BF16,推理用FP16
人工智能·算法·机器学习
KaMeidebaby9 小时前
卡梅德生物技术快报|蛋白 N 端测序在重组贻贝融合蛋白表征中的应用,解决原核表达序列偏移工艺难题
前端·人工智能·物联网·算法·百度