返回重复字母数最多的第一个单词

时间:2015-07-20 05:24:20

标签: javascript loops for-loop

这是来自coderbyte的简单设置的问题。很多人已经问过这个问题,但我真的很好奇我的解决方案有什么问题(我知道这是一个非常愚蠢和低效的解决方案......)

原始问题:

  

让函数LetterCountI(str)接受传递的str参数并返回具有最大重复字母数的第一个单词。例如:“今天,这是有史以来最伟大的一天!”应该返回最大,因为它有2个e(和2个t),并且它在之前也有2个e。如果没有重复字母的单词返回-1。单词将用空格分隔。

我的解决方案大部分时间都有效。但是,如果看起来输入的最后一个字不被我的代码所重视。例如,对于“a bb ccc”,将返回“bb”而不是“ccc”。但有趣的是,如果字符串只包含一个单词,结果是正确的。例如,“ccc”返回“ccc”。

请告诉我哪里错了。提前谢谢!

function LetterCountI(str) { 

  str.toLowerCase();

  var arr = str.split(" ");

  var count = 0;
  var word = "-1";

  for (var i = 0; i < arr.length; i++) {
   for (var a = 0; a < arr[i].length; a++) {
     var countNew = 0;
     for (var b = a + 1; b < arr[i].length; b++) {
       if(arr[i][a] === arr[i][b])
          countNew += 1;
     }
     if (countNew > count) {
       count = countNew;
       word = arr[i];
     }
   }
   return word;
  }


}       

5 个答案:

答案 0 :(得分:0)

我认为问题在于您将return语句放在最外层循环中。 它应该在你的内循环中。

所以你必须将return语句放在内循环中。

正确使用return

     if (countNew > count) {
       count = countNew; 
       word = arr[i];
     }
     return word;
    }
  }
} 

答案 1 :(得分:0)

您需要在循环之外移动return word;语句来修复您的版本。

我还将另一种依赖于Array.mapMath.max等内置javascript方法的算法放在一起,仅供参考。我跑了几个测试,它似乎快了几毫秒,但不是很多。

function LetterCountI(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;
            }           
        });

        //covert 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;
}

答案 2 :(得分:0)

请在下面找到代码的可用版本:

function LetterCountI(str) {
    str = str.toLowerCase();
    var arr = str.split(" ");
    var count = 0;
    var word = "-1";
    for (var i = 0; i < arr.length; i++) {
        for (var a = 0; a < arr[i].length; a++) {
            var countNew = 0;
            for (var b = a + 1; b < arr[i].length; b++) {
                if (arr[i][a] === arr[i][b])
                    countNew += 1;
            }
            if (countNew > count) {
                count = countNew;
                word = arr[i];
            }
        }
    }
    return word;
}

答案 3 :(得分:0)

更具功能性的编程风格的另一种解决方案:

<强>的JavaScript

function LetterCountI(str) {
  return ((str = str.split(' ').map(function(word) {
    var letters = word.split('').reduce(function(map, letter) {
          map[letter] = map.hasOwnProperty(letter) ? map[letter] + 1 : 1;
          return map;
        }, {}); // map of letters to number of occurrences in the word

    return {
      word: word,
      count: Object.keys(letters).filter(function(letter) {
        return letters[letter] > 1;
      }).length // number of repeated letters
    };
  }).sort(function(a, b) { // Sort words by number of repeated letters
    return b.count - a.count;
  }).shift()) && str.count && str.word) || -1; // return first word with maximum repeated letters or -1
}

console.log(LetterCountI('Today, is the greatest day ever!')); // => greatest

<强> Plunker

http://plnkr.co/edit/BRywasUkQ3KYdhRpBfU2?p=preview

答案 4 :(得分:0)

我建议使用正则表达式:/a+/g查找包含关键字a的字母列表。

我的例子:

var str = aa yyyyy bb cccc cc dd bbb;

拳头,找到不同单词的列表:

>>> ["a", "y", "b", "c", "d"]

对不同单词列表中的每个单词使用正则表达式:

var word = lstDiffWord[1];
             var
wordcount = str.match(new RegExp(word+'+','g')); 
console.log(wordcount);

>>>>["yyyyy"]

以下是完整示例:http://jsfiddle.net/sxro0sLq/4/

相关问题