解题思路:
正则匹配捕获/ (.*)[/, 捕获到则进栈一, 捕获 ] 则出栈的思路
解题代码
<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>
标签:index,tail,length,算法,str,相关,stack2,stack1 From: https://www.cnblogs.com/caijinghong/p/16918948.html