【发布时间】:2016-02-12 03:35:56
【问题描述】:
好吧,也许我最后一个问题还不够清楚。
我想返回字符串中重复字符最多的单词。
所以下面的字符串:
There/'s a passage that I got memorized, seems appropriate for this situation: Ezekiel 25,17.
将返回["appropriate"]。
但如果有多个单词具有相同数量的重复字符,我想将它们全部归还。所以下面的字符串
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"
【问题讨论】:
-
对于“克里斯的脾脏”,结果是
[Chris's, spleen]还是[spleen]? “男人的狗”是[man's, dog]还是[man, dog]? -
将
word从字符串更改为数组。如果当前计数大于最大计数,则将word设置为包含当前单词的数组。如果当前计数与最大计数相同,则将当前单词压入数组。否则,它与您拥有的完全相同。 -
如果你忽略了将单词标记为单词的难度,那么问题可以分解为小而简单的步骤。构建一个包含每个标记的“分数”的数组,跟踪最大分数是多少。然后取所有得分最高的单词。一个单词的评分函数非常简单……它只是一个循环。
-
我认为我不必担心 ' ,但是在你的场景中,[Chris's, spleen] 和 man's dog 没有重复的单词,所以它会返回 -1...
-
通过询问“man's dog”,我试图询问这个词是“man's”还是“man”。我认为你的第一个答案回答了这个问题。谢谢。
标签: javascript regex