这对于coderbyte来说是一个挑战我以为我会尝试使用不同的方法来解决它而不是循环,对象。它过去了,但并不完美。挑战的方向是:
让函数LetterCountI(str)传递str参数并返回重复字母数最多的第一个单词。例如:“今天,这是有史以来最伟大的一天!”应该返回最大,因为它有2个e(和2个t),并且它在之前也有2个e。如果没有重复字母的单词返回-1。单词将以空格分隔。
function LetterCountI(str){
var wordsAndLetters = {};
var count = 0;
var finalword;
str = str.split(" ");
for(var i = 0; i < str.length; i++){
wordsAndLetters[str[i]] = wordsAndLetters[str[i]] || 0;
}
function countWordLetters(strs){
strs = strs.split("");
var lettercount = {};
for(var i = 0; i <strs.length; i++){
lettercount[strs[i]] = lettercount[strs[i]] || 0;
lettercount[strs[i]]++;
}
return lettercount;
}
for(var words in wordsAndLetters){
wordsAndLetters[words] = countWordLetters(words);
var highestLetterFrequency = wordsAndLetters[words];
for(var values in highestLetterFrequency){
if(highestLetterFrequency[values] > count){
count = highestLetterFrequency[values];
finalword = words;
}
if(count !== 1){
return finalword;
}
}
}
return -1;
}
LetterCountI("today is the greatest day ever!");
很抱歉,如果某些变量名称令人困惑,我已经花了很长时间才弄清楚我做错了什么。如果您使用代码底部的参数,则返回“最大”,但应将参数更改为
LetterCountI("toddday is the greatttttest day ever!");
并记录'toddday',它应该记录'greatttttest'。我的代码完全错了吗?我知道如果参数是(“caatt dooog”)它应该记录'caatt',因为有4个重复的字母,但我并不担心我只关心它发现一个字母的最复发(但一定要如果你有解决方案我想听听!)。如果需要对变量进行任何更改以使此代码更具可读性,我们将不胜感激!
答案 0 :(得分:2)
代码的问题在于以下代码部分的定位:
if(count !== 1){
return finalword;
}
将其从当前位置移到return -1
之前,如下所示:
for(var words in wordsAndLetters){
wordsAndLetters[words] = countWordLetters(words);
var highestLetterFrequency = wordsAndLetters[words];
for(var values in highestLetterFrequency){
if(highestLetterFrequency[values] > count){
count = highestLetterFrequency[values];
finalword = words;
}
}
}
if(count !== 1){
return finalword;
}
return -1;
原始代码的问题在于您返回了第一个包含重复字符的单词,这意味着您的代码不足以检查后续单词是否包含更多重复字符。
另外,只是为了好玩,here is my alternative solution。
答案 1 :(得分:0)
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
function LetterCountI(str){
var temp = str.split(" ");
var final = '', weight = 0;
for(var i = 0; i < temp.length; ++i) {
var word = temp[i].split("");
if(word.getUnique().length < word.length) {
var diff = word.length - word.getUnique().length;
if(diff > weight){
weight = diff;
final = temp[i];
}
}
}
return final;
}
console.log(LetterCountI("Catt dooog"));
console.log(LetterCountI("toddday is the greatttttest day ever!"));
答案 2 :(得分:0)
Viva LinQ !!!!!
var resultPerWord = new Dictionary<string, int>();
var S = "toddday is the greatttttest day ever!";
foreach(var s in S.Split(' '))
{
var theArray =
from w in s
group w by w into g
orderby g.Count() descending
select new { Letter = g.Key, Occurrence = g.Count() };
resultPerWord.Add(s, theArray.First().Occurrence);
}
var r = "-1";
if (resultPerWord.Any(x => x.Value >1))
{
r = resultPerWord.OrderByDescending(x => x.Value).First().Key;
}