字符串智能重复

输入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]);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值