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;
    }
}; 
相关推荐
aaaameliaaa几秒前
结构体 结构体
c语言·笔记·算法
Xia__Quan16 分钟前
centos 共享文件夹
c++
怕浪猫33 分钟前
构建你自己的 AI Agent 发行版:从 Profile 定制到生产部署全流程
前端·后端·面试
hi_ro_a1 小时前
基于正倒排索引的boost搜索引擎
linux·c++·搜索引擎·项目
SendTomo1 小时前
.ico透明图标在线生成下载平台深度解析
大数据·数据结构·数据库·数据仓库·个人开发
有Li1 小时前
【AI答疑】MR数据预处理步骤
人工智能·笔记·算法·语言模型·医学生
神仙别闹1 小时前
基于 C++ MFC 实现的个人通讯录管理系统
c++
GG-_-Bond1 小时前
9.1kv存储持久化模拟面试
linux·c语言·数据结构·c++
盛世宏博北京1 小时前
多传感器数据融合算法:实现档案库房温湿度全域无死角监测
算法·档案温湿度
程序员阿鹏1 小时前
双亲委派机制
java·jvm·数据结构·后端