# 字符串解码
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
1
2
3
2
3
一 token压栈解法
/**
* @param {string} s
* @return {string}
*/
var decodeString = function (s) {
let stack = []
let rs = ''
let latest
s.split("").forEach(el => {
if (/[0-9]/.test(el)) {
if (latest&&latest.flag === 1||stack.length===0) {
//当前一个token在字符串阶段或者当前token栈为空时
latest = {
num: el,
str: '',
flag: 0
}
stack.push(latest)
} else {
latest.num += el
}
} else if (el === '[') {//标志进入字符串阶段
latest.flag = 1
} else if (el === ']') {//一段token结束阶段
stack.pop()//出栈
let getstr = latest.str.repeat(latest.num)//处理重复字符串
if (stack.length === 0) {
rs+=getstr
} else {//如果栈不为空,则把重复字符串添加至上一层栈的字符串上
latest = stack[stack.length - 1]
latest.str += getstr
}
} else {//字符串阶段
if (stack.length === 0) {
rs+=el
}else{
latest.flag = 1
latest.str += el
}
}
})
return rs
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
二 正则解法
TODO