解题思路:

正则匹配捕获/ (.*)[/, 捕获到则进栈一, 捕获 ] 则出栈的思路

 

 解题代码

<script>
    var str = '2[3[a]2[1[b]2[c]]]'
    // var str = '2[3[a]1[b]]'

    function smartRepeat(str) {
      let stack1 = [],
        stack2 = [],
        index = 0,
        tail = str

      while (index < str.length) {
        if (/^(\d+)\[/g.test(tail)) {
          stack1.push(RegExp.$1)
          stack2.push('')

          index += RegExp.$1.length + 1
          tail = str.substring(index)
        } else if (/^(\w+)\]/g.test(tail)) {
          let value = RegExp.$1
          let times = stack1.pop()
          stack2.pop()
          stack2[stack2.length - 1] += value.repeat(times)

          index += RegExp.$1.length + 1
          tail = str.substring(index)
        } else {
          let times = stack1.pop()
          let value = stack2.pop()
          index++
          if (stack1.length == 0 && stack2.length == 0) {
            return value.repeat(times)
          }

          stack2[stack2.length - 1] += value.repeat(times)
        }
      }
    }

    console.log(smartRepeat(str))
  </script>

 

posted on 2022-11-23 16:54  京鸿一瞥  阅读(37)  评论(0编辑  收藏  举报