智能重复
/*
试着编写smartRepeat 使用栈结构 ,自己编写栈结构 ,需要完成栈的基本操作,入栈 ,出栈,销毁栈,栈的初始化
将 3[abc] ---> abcabcabc
将 3[2[a]2[b]] ---> aabbaabbaabb
将 3[2[a]2[2b]] ---> aa2b2b aa2b2b aa2b2b (最终返回字符串中间不含有空格,空格是为了方便看,以下同样)
将 3[2[a]10[2b]] ---> aa2b2b2b2b2b2b2b2b2b2b aa2b2b2b2b2b2b2b2b2b2b aa2b22bb2b2b2b2b2b2b2b
将 2[1[af]3[b]2[3[c]2[def]]] ---> afbbbcccdefdefcccdefdef afbbbcccdefdefcccdefdef
不考虑
3[a][b] ---> 极端情况此种方式错误 ---需要写成 -->3[a]1[b]
3[a3[b]] ---> 极端情况此种方式错误 ---需要写成 -->3[1[a]3[b]]
*/
let str = "3[2[a]10[2b]]" // ---> abb
function smartRepeat(templateStr) {
let index = 0; // 指针
// 两个栈
let numStack = []; // 数字栈
let strStack = []; // 字符栈
// 剩余部分
let rest = templateStr
while (index < templateStr.length - 1) {
rest = templateStr.substring(index)
// 看当前部分是否有是数字开头和[ 开头
if (/^\d+\[/.test(rest)) {
// 把数字压栈 , 字符串压栈
let times = Number(rest.match(/^(\d+)\[/)[1])
times
// 如果是数值则移动 数字的长度 + 1 为什么+1 加一位是加 [ 的长度
index += times.toString().length + 1;
// 将数字压栈
numStack.push(times)
// 将空字符压栈
strStack.push('')
} else if (/^\w+/.test(rest)) {
// 匹配字母或数字或下划线或汉字 等价于 '[^A-Za-z0-9_]'。
let word = rest.match(/^(\w+)\]/)[1];
strStack[strStack.length - 1] = word;
// 移动指针 移动 word 词的长度
index += word.length
} else if (rest[0] === ']') {
// 如果这个字符串是 " ] " , 那么将①numStack 弹栈 ②strStack弹栈,把字符串栈的新栈顶的元素重复刚刚弹出的那个字符串指定次数拼接到新的栈顶上
let times = numStack.pop();
let word = strStack.pop();
/*
repeat() 构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。
str.repeat(count)
count:
介于 0 和 +Infinity 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。
return
包含指定字符串的指定数量副本的新字符串。
*/
strStack[strStack.length - 1] += word.repeat(times)
index++;
}
}
// while 结束后,numStack 和 strStack 肯定还会剩余一项, 最终返回---> strStack[0] 中剩余这一项,重复numStack[0]的次数的字符串
return strStack[0].repeat(numStack[0])
}
// smartRepeat(str) //?
console.log(smartRepeat(str))