LeetCode 394. Decode String All In One
LeetCode 394. Decode String All In One
LeetCode 394. 解码字符串 算法题解
errors
function decodeString(s: string): string {
let stack = [];
for(let i = 0; i < s.length; i ++) {
// 嵌套 []
let str = [];
while(stack.length && s[i] === `]`) {
let temp = stack.pop();
if(temp !== `[`) {
str.push(temp);
} else {
let n = stack.pop();
str = [...str.join(``).repeat(n)];
}
stack.push(str.reverse().join(``));
}
stack.push(s[i]);
}
return stack.join(``);
};
/*
Wrong Answer
23 / 34 testcases passed
Input
s =
"100[leetcode]"
Use Testcase
*/
solutions
function decodeString(s: string): string {
const stack: string[] = [];
for (let c of s) {
stack.push(c);
// 1. close square bracket
if (stack[stack.length - 1] === `]`) {
// remove `]`
stack.pop();
// collect strings
const str: string[] = [];
while (stack[stack.length - 1] !== `[`) {
str.unshift(stack.pop());
}
// remove `[`
stack.pop();
// collect numbers
const num: string[] = [];
while (`0123456789`.includes(stack[stack.length - 1])) {
num.unshift(stack.pop());
}
// repeat
let temp = str.join(``).repeat(+num.join(``));
stack.push(temp);
}
}
return stack.join("");
};
function decodeString(s: string): string {
const digits = '0123456789';
const stack: [string, number][] = []
let str = ''
let multiplier = 0
for (let c of s) {
if (digits.includes(c)) {
// fix: int number range [1, 300]. ✅
// 10
// 100
multiplier = multiplier * 10 + parseInt(c)
// ❌
// multiplier = parseInt(c)
} else if (c === '[') {
stack.push([str, multiplier])
// reset
str = ''
multiplier = 0
} else if (c === ']') {
const [prevStr, prevMultiplier] = stack.pop()
str = prevStr + str.repeat(prevMultiplier)
} else {
str += c
}
}
return str
}
demos
refs
https://leetcode.com/studyplan/leetcode-75/
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/18223600
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2023-05-31 How to fix the problem that Raspberry Pi cannot use the root user for SSH login All In One
2023-05-31 macOS 如何隐藏掉桌面上出现的 U盘符号 All In One
2023-05-31 How to modify the hostname and username and password of Raspberry Pi All In One
2023-05-31 Linux shell standard input bugs All In One
2022-05-31 Apple iPhone 12 Pro 扬声器水流声 bug All In One
2022-05-31 Media Source Extensions All In One
2021-05-31 ES6 destructuring assignment & default value & rename All In One