标签:buffer 字符串 lse return split start spl stack ons
将一个带格式的字符串转换成一个正常的字符串。仔细观察 ,是要用到字符串的repeat方法,中括号前的数字为重复次数,括号内的数据需要再次转译成正常字符串。
var numberMap = new Array(10).fill(0).reduce((obj, el, index) => {
obj[index] = 1
return obj
}, {});
function helper(arr, start) {
var num = 1, firstInt = true, buffer = '', res = ''
for (var i = start; i < arr.length; i++) {
var c = arr[i];
if (numberMap[c]) {
c = c - 0;
if (firstInt) {
res += buffer;
buffer = '';
num = c
firstInt = false
} else {
num = num * 10 + c;
}
continue
}
if (c === '[') {
firstInt = true;
buffer = '';
var obj = helper(arr, i + 1);
i = obj.index;
res += obj.str.repeat(num);
continue
}
if (c === ']') {
return {
str: res + buffer,
index: i
}
continue
}
buffer += c
}
if (buffer.length) {
res += buffer
}
return {
str: res,
index: i
}
}
function decodeString(s) {
var arr = s.split('');
var obj = helper(arr, 0);
console.log(obj)
return obj.str
}
var str = decodeString('3[a]2[b4[F]c]');
decodeString('3[a]2[bc]')
decodeString('cccc')
decodeString("3[a2[c]]")
decodeString("2[abc]3[cd]ef")
另一个好妖的实现
function decodeString(s) {
const stack = []
let i = 0
let curMulti = 0
let curStr = []
while (i < s.length) {
const c = s[i]
if (c >= '0' && c <= '9') {
curMulti = (curMulti * 10) + (c - '0')
} else if (c === '[') {
stack.push(curMulti)
stack.push(curStr)
curMulti = 0
curStr = []
} else if (c === ']') {
const lastStr = stack.pop()
curMulti = stack.pop()
for (let k = 0; k < curMulti; k++) {
for (const cc of curStr) {
lastStr.push(cc)
}
}
curMulti = 0
curStr = lastStr
} else {
curStr.push(c)
}
i+=1
}
return curStr.join('')
}
标签:buffer 字符串 lse return split start spl stack ons
原文地址:https://www.cnblogs.com/rubylouvre/p/12089271.html