Skip to content

Commit

Permalink
394.字符串解码
Browse files Browse the repository at this point in the history
  • Loading branch information
cslc-ubm committed Apr 2, 2021
1 parent f8e2344 commit 255e6b9
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 394.字符串解码.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* @param {string} s
* @return {string}
*/
function decodeString(s) {
let strStack = []
let numStack = []
let res = ''
let num = 0
for (let c of s) {
if (/\d/.test(c)) {
num = num * 10 + +c // 算出倍数
} else if (c === '[') {
numStack.push(num) // 倍数num进入栈等待
strStack.push(res) // result串入栈
res = ''
num = 0
} else if (c === ']') {
let repeatTimes = numStack.pop() // 获取拷贝次数
res = strStack.pop() + res.repeat(repeatTimes)
} else {
res += c
}
}
console.log(res)
return res
}
// 测试用例
decodeString('3[a2[c]]')

/** 示例 1:
输入:s = "3[a]2[bc]"
输出:"aaabcbc"
示例 2:
输入:s = "3[a2[c]]"
输出:"accaccacc"
示例 3:
输入:s = "2[abc]3[cd]ef"
输出:"abcabccdcdcdef"
*/

0 comments on commit 255e6b9

Please sign in to comment.