当前位置:网站首页>LeetCode:394. 字符串解码
LeetCode:394. 字符串解码
2022-07-06 08:44:00 【Bertil】
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例 1:
输入:s = "3[a]2[bc]"
输出:"aaabcbc"
示例 2:
输入:s = "3[a2[c]]"
输出:"accaccacc"
示例 3:
输入:s = "2[abc]3[cd]ef"
输出:"abcabccdcdcdef"
示例 4:
输入:s = "abc3[cd]xyz"
输出:"abccdcdcdxyz"
提示:
- 1 <= s.length <= 30
- s 由小写英文字母、数字和方括号 ‘[]’ 组成
- s 保证是一个 有效 的输入。
- s 中所有整数的取值范围为 [1, 300]
解题思路
1.由内到外,层层解决[ ],需要保持对字符的记忆,因此用栈
2.入栈时机:遇到 [ 意味着要先解决内部的,外部的数字和字母去栈里等
- 当遇到[,已经扫描的数字就是“倍数”,入栈暂存
- 当遇到[,已经扫描的字母也入栈等待,等括号里的解码完了,就能一起参与构建字符串
3.出栈时机:遇到 ] 说明内层的扫描完了,栈顶元素(最近遇到的“倍数”和字母)可以出栈了,共同参与子串的构建
代码
/** * @param {string} s * @return {string} */
var decodeString = function(s) {
let numStack = []; // 存倍数的栈
let strStack = []; // 存 待拼接的str 的栈
let num = 0; // 临时倍数
let result = ''; // 临时字符串
for (const char of s) {
// 逐字符扫描
if (!isNaN(char)) {
// 遇到数字
num = num * 10 + Number(char); // 算出倍数
} else if (char == '[') {
// 遇到 [
strStack.push(result); // result串入栈
result = '';
numStack.push(num); // 倍数num进入栈等待
num = 0;
} else if (char == ']') {
// 遇到 ],两个栈的栈顶出栈
let repeatTimes = numStack.pop(); // 获取拷贝次数
result = strStack.pop() + result.repeat(repeatTimes); // 构建子串
} else {
result += char; // 遇到字母,追加给result串
}
}
return result;
};
边栏推荐
- View computer devices in LAN
- TCP/IP协议
- 2022.02.13 - 238. Maximum number of "balloons"
- Current situation and trend of character animation
- pytorch训练好的模型在加载和保存过程中的问题
- LeetCode:剑指 Offer 42. 连续子数组的最大和
- pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof
- 游戏解包的危害及资源加密的重要性
- Precise query of tree tree
- Swagger setting field required is mandatory
猜你喜欢
随机推荐
China vanadium battery Market Research and future prospects report (2022 Edition)
JVM performance tuning and practical basic theory - Part 1
Precise query of tree tree
Warning in install. packages : package ‘RGtk2’ is not available for this version of R
TP-LINK 企业路由器 PPTP 配置
Unsupported operation exception
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
Chrome浏览器的crash问题
2022.02.13 - NC001. Reverse linked list
China Light conveyor belt in-depth research and investment strategy report (2022 Edition)
China high purity silver nitrate Market Research and investment strategy report (2022 Edition)
sublime text的编写程序时的Tab和空格缩进问题
Charging interface docking tutorial of enterprise and micro service provider platform
pytorch训练好的模型在加载和保存过程中的问题
The network model established by torch is displayed by torch viz
visdom可视化实现与检查介绍
POI add write excel file
Revit 二次开发 HOF 方式调用transaction
To effectively improve the quality of software products, find a third-party software evaluation organization
Colorlog combined with logging to print colored logs








