在JavaScript中解码字符串的函数
给我们一个编码后的字符串,我们需要通过一个返回其解码后的字符串的函数对其进行处理。
编码规则是-
n[encodedString], where the encodedString inside the square brackets is being repeated exactly n times.
并且保证n为正整数。
我们可以假设输入字符串始终有效;没有多余的空格,方括号格式正确等。
例如-如果输入为-
const str = "3[a]2[bc]";
那么输出应该是-
const output: "aaabcbc";
示例
为此的代码将是-
const str = "3[a]2[bc]";
const helper = (str = '') => {
return str.replace(/(\d+\[\w+\])/gi, item => {
let match = /(\d+)\[(\w+)\]/.exec(item);
let repeat = parseInt(match[1]);
let pattern = match[2];
let result = "";
while(repeat−− > 0) {
result += pattern;
}
return result;
});
};
const decodeString = function(str) {
while(/\d+\[\w+\]/gi.test(str)) {
str = helper(str);
}
return str;
};
console.log(decodeString(str));输出结果
控制台中的输出将是-
aaabcbc