394. 字符串解码
- 题号:394
- 来源:LeetCode
- 难度:中等
- 标签:
栈字符串 - 语言:TypeScript
- 解法:1 个
- 作者:lmliheng
- 最近更新:2026-09-27
TypeScript · O(n) 时间 · O(n) 空间 · 更新于 2026-09-27
栈保存外层重复次数与已拼好的前缀串
typescript
/**
* @difficulty medium
* @tags 栈,字符串
* @time O(n)
* @space O(n)
* @note 栈保存外层重复次数与已拼好的前缀串
* @394. 字符串解码
*/
let s = "3[a]2[bc]"
let num = 0
let str = ''
let stack: [number, string][] = []
for (let ch of s) {
if (47 < ch.charCodeAt(0) && 58 > ch.charCodeAt(0)) {
num = num * 10 + (+ch)
} else if (ch === '[') {
stack.push([num, str])
num = 0
str = ''
} else if (ch === ']') {
let arr = stack.pop()!
console.log('arr:',arr)
str = arr[1]+str.repeat(arr[0])
} else {
str = str + ch
}
console.log('=======', ch)
console.log(num)
console.log(str)
console.log(stack)
}
console.log(str)在 GitHub 上查看题目所在目录:lmliheng/algorithm