gpt4 book ai didi

javascript - 使用 javascript 计算重复单词数

转载 作者:行者123 更新时间:2023-12-01 03:56:54 25 4
gpt4 key购买 nike

我正在尝试解决这个练习,但我有点卡住了,这就是我现在所拥有的,我正在尝试迭代字符串,增加索引,每个单词加一个

"Write a function to perform basic string compression using the counts of repeated characters e.g "aabcccccaaa" would become "a2b1c5a3", if the compressed string would not become smaller than the original, just print the original"

function countWords() {
var word = "aabcccccaaa";
var result = "";
var counter = 0;

for (var i = 0; i <= word.length; i++) {
if (word[i] != word[i + 1]) {
result = result + word[i] + counter;
counter = 0;
i++;
} else {
counter++;
i++;
}
}

console.log(result);

if (result.length < word.length)
console.log(result)
else
console.log(word);
}

console.log(countWords())

最佳答案

您可以使用正则表达式的强大功能,减少数组和条件三元。

function compress(input) {
var re = /(.)\1+|./gi;
var match = input.match(re);
var output = match.reduce(function (previousValue, currentValue) {
return previousValue + (currentValue.charAt(0) + currentValue.length);
}, "");
output = (output.length < input.length) ? output : input;
return output;
}
console.log(compress("aabcccccaaa"));

关于javascript - 使用 javascript 计算重复单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42585019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com