返回句子中最大数量的重复字符
Return greatest number of repeated characters in a sentence
好吧,也许我的最后一个问题我不够清楚。
我想返回字符串中重复字符最多的单词。
所以下面的字符串:
There/'s a passage that I got memorized, seems appropriate for this situation: Ezekiel 25,17.
会返回["appropriate"]
.
但是,如果有多个单词具有相同数量的重复字符,我想将它们全部返回。 所以下面的字符串
Hello all from Boston
会返回["Hello", "all", "boston"]
这是我到目前为止的代码。此代码取自另一个堆栈溢出线程
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);
}
是的,你可以做到。 请尝试以下脚本。
function largest(arr){
var sortArr = arr.sort(function(a,b){return b.length - a.length});
return sortArr;
}
function returnRepeatChar(str){
return largest(str.toLowerCase().split(" "));
}
//This function return the sorted of the given string
var sorted = returnRepeatChar("There''s a passage that I got memorized, seems appropriate for this situation: Ezekiel 25,17.");
alert(sorted);
相关文章:
- 我如何找到一个句子中的所有空格并替换忽略它们
- 在JavaScript中输出转义字符
- 不同浏览器中的空白字符正则表达式行为
- Regex匹配除“”之外的所有字符;.js”;
- 如何使用Javascript在给定的句子中找到大写单词并在其前面添加一个字符
- 获取特殊字符后没有单词的句子
- 计算JavaScript中句子(数组)中字符(数组)的出现次数
- 如何使用客户端 Javascript 将句子中的日语字符拆分为数组
- 返回句子中最大数量的重复字符
- 将句子字符串拆分为单词数组,然后将单词数组拆分为单词数组中的字符数组
- 在句子末尾插入随机字符
- 在 JavaScript 中反转句子而不反转字符
- 对照测试两个句子的起始字符
- “阅读更多”的开关不是字符的数量,而是句子的长度
- 如何将Javascript字符串拆分为少于140个字符的句子
- 从具有括号并在括号中具有一定数量的固定值的句子中拆分字符
- Regex,用于搜索输入的句子,但包含特殊字符
- 将两个句子分成单词和字符,并分别展示
- 单击时确定句子的字符
- 如何创建正则表达式以匹配句子中的第一个字符