在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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志