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;
    }
}; 
相关推荐
Darling噜啦啦1 小时前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
swipe2 小时前
正则表达式入门到进阶:从表单校验到手写模板引擎
前端·javascript·面试
神奇小汤圆3 小时前
RAG大厂面试题汇总:向量检索、混合检索、Rerank、幻觉处理高频问题
面试
clint4563 小时前
C++进阶(1)——前景提要
c++
用户497863050734 小时前
(一)小红的数组操作
算法·编程语言
假如让我当三天老蒯5 小时前
回归基本功:Map/Set 与 WeakMap/WeakSet 的区别
前端·面试
夜悊7 小时前
C++代码示例:进制数简单生成工具
c++
怕浪猫7 小时前
Electron 系列文章封面图
算法·架构·前端框架
郝学胜_神的一滴8 小时前
CMake 021: IF 条件判据详诠
c++·cmake
假如让我当三天老蒯8 小时前
回归基本功!前端的解构赋值、扩展运算符、剩余参数
前端·面试