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
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://leetcode.com/studyplan/leetcode-75/
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/18223600
未经授权禁止转载,违者必究!