[英]Uncompress a String, repeat chars `n` times
Write a function, uncompress, that takes in a string as an argument.
编写一个 function,解压缩,将字符串作为参数。 The input string will be formatted into multiple groups according to the following pattern:
输入字符串将根据以下模式格式化为多个组:
number + char
数字 + 字符
for example, '2c' or '3a'.
例如,“2c”或“3a”。
The function should return an uncompressed version of the string where each 'char' of a group is repeated 'number' times consecutively.
function 应返回字符串的未压缩版本,其中组的每个“字符”连续重复“数字”次。 You may assume that the input string is well-formed according to the previously mentioned pattern.
您可以假设输入字符串按照前面提到的模式格式正确。
test_00: uncompress("2c3a1t");
test_00:解压缩(“2c3a1t”); // -> 'ccaaat'
// -> 'ccaaat'
Here is my code which is using a stack.这是我使用堆栈的代码。 The problem is that it's only returning 'cc' and I can't figure out why.
问题是它只返回'cc',我不知道为什么。 I've console logged what goes into the IF ELSE and I'm hitting both so I don't understand why nothing gets pushed to the stack.
我已经控制台记录了进入 IF ELSE 的内容,并且我都击中了两者,所以我不明白为什么没有任何东西被推入堆栈。
Would really appreciate the help if someone can spot what I'm missing.如果有人能发现我遗漏的东西,我将不胜感激。
const uncompress = (s) => { const nums = '23456789'; const stack = []; for (let char of s) { if (nums.includes(char)) { stack.push(Number(char)); } else { const num = stack.pop(); stack.push(char.repeat(num)); }; }; return stack.join(''); }; console.log(uncompress("2c3a1t")); // -> 'ccaaat'
Here's how I would do it:这是我的做法:
Split the string up into pairs of numbers and chars:将字符串拆分为成对的数字和字符:
str.match(/\d+[a-zA-Z]/g)
And reduce that array to a string, while taking each value from the array, getting the char from it ( cv.match(/[a-zA-Z]/)[0]
) and repeating it according to the number ( .repeat(parseInt(cv))
)并将该数组简化为一个字符串,同时从数组中获取每个值,从中获取字符(
cv.match(/[a-zA-Z]/)[0]
)并根据数字重复它( .repeat(parseInt(cv))
)
const uncompress = str => str.match(/\d+[a-zA-Z]/g).reduce((acc, cv) => acc + cv.match(/[a-zA-Z]/)[0].repeat(parseInt(cv)), "") console.log(uncompress("2c3a1t")) console.log(uncompress("27b1d8g"))
And just like that I was able to write the code which passed the test case:就像这样,我能够编写通过测试用例的代码:
const nums = '123456789';
const stack = [];
for (let char of s) {
if (nums.includes(char)) {
stack.push(Number(char));
} else {
let num = '';
while (nums.includes(stack[stack.length - 1])) {
num += stack.pop();
}
stack.push(char.repeat(num));
};
};
return stack.join('');
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.