打印规定循环字符串
题目: 给定一个字符串,按以下规则输出其中的字母,如下:
3[abc]
输出:abcabcabc
3[2[a]2[b]]
输出:aabbaabbaabb
2[1[a]3[b]2[3[c]4[d]]]
输出:abbbcccddddcccdddabbbcccddddcccddd
1
2
3
4
5
6
2
3
4
5
6
来源:栈的运用
题解:
利用栈先进后出的原理,匹配出入栈标识[、],代码如下
function smartRepeat(templateStr) {
// 指针
var index = 0
// 栈1
var stack1 = []
// 栈2
var stack2 = []
// 尾部
var rest = templateStr
while(index < templateStr.length -1) {
// 改变尾部 剩余部分
rest = templateStr.substring(index)
// 检测是否以数字和[开头
if (/^\d+\[/.test(rest)) {
// 将数字入栈1
// 如果这个字符是数字,那么就将数字压入 stack1栈,把`空字符串压入stack2栈,
let times = Number(rest.match(/^(\d+)\[/)[1])
stack1.push(times)
// 将空字符串入栈2
stack2.push('')
// 让指针后移 times这个数字多少就后移多少位 +1
// +1 是[括号
index += times.toString().length + 1
} else if (/^\w+\]/.test(rest)) {
// 如果这个字符是字母,那么此时就把stack2栈顶这一项改为这个字母,
let word = rest.match(/^(\w+)\]/)[1]
// 字母和]开头
stack2[stack2.length-1] = word
// 让指针后移 word这个数字多少就后移多少位
index += word.length
} else if(rest[0] == ']'){
// 如果这个字符是],那么就将数字从 stack1 栈中弹出,把 stack2的栈顶元素重复 stack1中 弹栈的数字的次数`,
// 然后将其从stack2中弹出,拼接到stack2的新栈顶上。
let times = stack1.pop()
let word = stack2.pop()
// repeat是h5中新增的方法 比如: 'a'.repeat(2) = 'aa'
stack2[stack2.length -1 ] += word.repeat(times)
index++
}
console.log(index, stack1,stack2);
}
// while遍历结束 stack1和stack2各剩一项
return stack2[0].repeat(stack1[0])
}
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
44
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
44
上次更新: 2025/09/05, 8:09:00