输入3[2[c]3[b]],打印ccbbbccbbbccbbb。
解题思路:利用栈来进行弹出,压栈即可。
function smartRepeat(str) {
let index = 0;
let stackNum = [];
let stackStr = [];
let childStr = "";
//3[2[c]3[b]]
while (index < str.length - 1) {
childStr = str.substring(index);
//看当前剩余字符串是否是字符开头
if (/^\d+\[/.test(childStr)) {
//得到数字
let times = Number.parseInt(childStr.match(/^(\d+)\[/)[1]);
//把数字,空字符串压栈
stackNum.push(times);
stackStr.push("");
index += times.toString().length + 1;
} else if(/^\w+\]/.test(childStr)) {
//如果是字符,那么此时就把栈顶这项改为该字母
let word = childStr.match(/^(\w+)\]/)[1];
stackStr[stackStr.length-1] = word;
//移动指针
index += word.length;
}else if(childStr[0] === ']'){
/**
如果这个字符是],那么将数字弹栈,stackStr弹栈,把字符串的栈顶元素重复刚刚的这个次数,
拼接到新栈顶上
*/
let times = stackNum.pop();
let word = stackStr.pop();
stackStr[stackStr.length-1] += word.repeat(times);
index++;
}
}
//while循环结束后,两个栈中肯定还剩下最后一项
return stackStr[0].repeat(stackNum[0]);
}