解题思路:
正则匹配捕获/ (.*)[/, 捕获到则进栈一, 捕获 ] 则出栈的思路
解题代码
<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>
人生很漫长,或许我只是你人生中微不足道的一小段,只是你人生中的惊鸿一瞥。