gpt4 book ai didi

javascript - 返回句子中重复字符的最大数量

转载 作者:行者123 更新时间:2023-12-03 07:42:20 25 4
gpt4 key购买 nike

好吧,也许我最后一个问题还不够清楚。

我想返回字符串中重复字符最多的单词。

所以下面的字符串:

There/'s a passage that I got memorized, seems appropriate for this situation: Ezekiel 25,17.

将返回[“适当的”]

但是如果有多个单词具有相同数量的重复字符,我想将它们全部返回。所以下面的字符串

Hello all from Boston

将返回["Hello", "all", "boston"]

这是我到目前为止的代码。此代码取自另一个 stackoverflow thread

function returnRepeatChar(str){
var maxCount = 0;
var word = '-1';

//split string into words based on spaces and count repeated characters
str.toLowerCase().split(" ").forEach(function(currentWord){
var hash = {};

//split word into characters and increment a hash map for repeated values
currentWord.split('').forEach(function(letter){
if (hash.hasOwnProperty(letter)){
hash[letter]++;
} else {
hash[letter] = 1;
}
});

//convert the hash map to an array of character counts
var characterCounts = Object.keys(hash).map(function(key){
return hash[key];
});

//find the maximum value in the squashed array
var currentMaxRepeatedCount = Math.max.apply(null, characterCounts);

//if the current word has a higher repeat count than previous max, replace it
if (currentMaxRepeatedCount > maxCount){
maxCount = currentMaxRepeatedCount;
word = currentWord;
}

});
return word;
}

console.log(returnRepeatChar("There/'s a passage that I got memorized, seems appropiate for this situation: Ezekiel 25,17.")); //"appropriate"

最佳答案

对您的代码进行以下简单更改。

var word = "-1";

变成:

var word = [];

更新word的代码变为:

//if the current word has a higher repeat count than previous max, replace it 
if (currentMaxRepeatedCount > maxCount){
maxCount = currentMaxRepeatedCount;
word = [currentWord];
} else if (currentMaxRepeatedCount == maxCount) {
// If it's the same as the max, add it to the list
word.push(currentWord);
}

关于javascript - 返回句子中重复字符的最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35354386/

25 4 0
文章推荐: javascript - 当我拖动连接到 Web Audio API 增益节点的 slider 时,它会弹出并单击。拖动时音量没有平滑变化
文章推荐: javascript voice.synthesis.speak 属性
文章推荐: javascript -