gpt4 book ai didi

JavaScript |返回字符串中最常见的多个字符

转载 作者:行者123 更新时间:2023-12-01 02:05:59 24 4
gpt4 key购买 nike

所以我正在学习如何返回字符串中最常见的字符。我知道如果只有一个字符出现最多,即“javascript”中的“a”出现两次,其余字符仅出现一次,我知道该怎么做。但如果字符串是“javascript prototype”,则有两个字符出现最多,即“p”和“t”。我正在使用 _.invert() 来获取字母出现次数最多的数字的值,但由于“p”和“t”都等于 3,所以我可以返回它们。我预计输出是 “pt”

// Return the character that is most common in a string
// ex. maxCharacter('javascript') == 'a'
// Return multiple characters that are most common in a string
// ex. maxCharacter('javascript prototype') == 'p t'
function maxCharacter(str) {


const charMap = {};
let maxNum = 0;
let maxChar = '';

str.replace(/\s/gi, '').split('').forEach(function(char){
if(charMap[char]){
charMap[char]++;
} else {
charMap[char] = 1;
}
});


for(let char in charMap){
if(charMap[char] > maxNum) {
maxNum = charMap[char];
maxChar = (_.invert(charMap))[maxNum];
}
}
return maxChar;
}



// Call Function
const output = maxCharacter('javascript prototype');

console.log(output);

最佳答案

通过 spreading 查找 charMap 中的最大数字Object.values()进入Math.max() 。然后使用Array.filter()仅获取具有最大值的键,并用空格将它们连接起来:

function maxCharacter(str) {
const charMap = {};

str.replace(/\s/gi, '').split('').forEach(function(char){
if(charMap[char]){
charMap[char]++;
} else {
charMap[char] = 1;
}
});

const max = Math.max(...Object.values(charMap));

return Object.keys(charMap)
.filter((c) => charMap[c] === max)
.join(' ');
}

console.log(maxCharacter('javascript')); // a
console.log(maxCharacter('javascript prototype')); // p t

关于JavaScript |返回字符串中最常见的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50106031/

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