Letter Count: return the first word with the greatest number of repeated letters

一世执手 提交于 2019-12-10 12:08:43

问题


Can anyone help me out with the bug? This is a letter count challenge that you need to return the first word with greatest number of repeated letters, e.g.: Input = "Hello apple pie" Output = Hello

I tried many different ways to debug my code and notice that the string didn't pass into the while loop, but I have no ideas why. Can anyone explain?

function LetterCount(str) { 
  str = str.split(" ");
  var index = 0;
  while(index >= str.length){
  	for(var i = 0; i < str.length; i++){
      var str1 = str[i].split("").sort();
      for(var k = 0; k < str1.length; k++){
        
      	if(index === 0 && str1[k] === str[k+1]){
          return str[i];
      	}
      	else if(index > 0 && str1[k] === str[k+1]){
          return str[i];
      	}
      }
    }
    index++;
  }
  return -1;
}

回答1:


Here's some regex magic to pull it off as well. ;)

function LetterCount(str) {
    var parts = str.replace(/(\s+)|([A-Z]*?)([A-Z])(\3+)([A-Z]*)|([A-Z]+)/gi, "$1$2$3$4$5$6,$3$4,").split(',');
    var firstIndexOfMaxLetters, maxCount = 0;
    for (var i = 1; i < parts.length; i += 2)
        if (parts[i].length > maxCount)
            { maxCount = parts[i].length; firstIndexOfMaxLetters = i; }
    return firstIndexOfMaxLetters ? parts[firstIndexOfMaxLetters-1] : "";
}
LetterCount("Hi apPple pie")

Output: "apPple"

The regex turns the string into this:

["Hi", "", " ", "", "apPple", "pPp", " ", "", "pie", ""]

... where every second item in the array is the repeating letters (if any, or blank otherwise), and the word is before it. ;)




回答2:


Taking a quick look as Ewald said your index is 0 so while loop won't be execute. I think will be easier if you store letters on a dictionary.

var niceDict = {};
//save letter and set initial value to zero
var letter = 'e';
niceDict[letter] = 0; // or niceDict['e'] = 0;
//incremente value
niceDict[letter]++;


来源:https://stackoverflow.com/questions/29524330/letter-count-return-the-first-word-with-the-greatest-number-of-repeated-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!