题目:有一个字符串:'2[3[a]2[3[u]2[p]]]]',将他转换成
aaauuuppuuuppaaauuuppuuupp
案例:
3[a] 转换后: aaa
2[3[a]2[b]] 转换后: aaabbaaabb
实现
let msg = '2[3[a]2[3[u]2[p]]]'
console.log(msg)
function handleStr(str) {
let stack1 = [] // 存放数字
let stack2 = [''] // 存放字母
let index = 0
while(index < str.length) {
// console.log(stack2)
let nowStr = str.substring(index)
if(/^\d+\[/.test(nowStr)){
let num = nowStr.match(/^(\d+)\[/)[1]
index += num.length + 1
stack1.push(Number(num))
stack2.push('')
} else if(/^\w+\]/.test(nowStr)){
let word = nowStr.match(/^(\w+)\]/)[1]
index += word.length
console.log(stack2, stack2.length - 1)
stack2[stack2.length - 1] = word
} else if(nowStr[0] == ']'){
let num = stack1.pop()
let subStr = stack2.pop()
stack2[stack2.length - 1] += subStr.repeat(num)
index++
}
}
console.log(stack2, stack1)
return stack2[0]
}
handleStr(msg)
说明:每个 [ 前面必须有数字才算,否则结果不对。这里使用的是栈的思想来解决的