var str = "2[1[a]3[b]2[3[c]4[d]]]"; functionsmartRepeat(str) { var index = 0, stack1 = [], stack2 = [], rest = str; while (index < str.length - 1) { rest = str.substring(index); if (/^\d+\[/.test(rest)) { // 剩余字符串以数字开头,1)取出这个数字压入数字栈;2)字符栈压入空字符串;3)指针后移至[之后 let times = Number(rest.match(/^(\d+)\[/)[1]); stack1.push(times); stack2.push(''); index += times.toString().length + 1; } elseif (/^\w+\]/.test(rest)) { // 剩余字符串以字母开头,1)取出字符并压入字符栈;2)指针后移至字符之后 let word = rest.match(/^(\w+)\]/)[1]; stack2[stack2.length - 1] = word; index += word.length; } elseif (rest[0] == ']'){ // 剩余字符串以]开头,1)数字栈弹栈;2)字符栈弹栈3)弹出的字符重复刚才弹栈的次数并拼接到新的字符栈顶 let times = stack1.pop(); let word = stack2.pop(); stack2[stack2.length - 1] += word.repeat(times) index++; } } // 当while结束后,stack1和stack2中肯定存在剩余1项,返回stack2中剩余的这一项,重复stack1中剩余的这一项的次数,返回这个字符串 return stack2[0].repeat(stack1[0]) }
判断标签是否闭合
使用while与replace
1 2 3 4 5 6 7 8 9 10
functionisValid(s) { while (s.length) { let temp = s; s = s.replace('()', ''); s = s.replace('[]', ''); s = s.replace('{}', ''); if (s == temp) returnfalse } returntrue; }