Return the first word with the greatest number of repeated letters

僤鯓⒐⒋嵵緔 提交于 2019-12-30 14:44:12

问题


This is a question from coderbyte’s easy set. Many people asked about it already, but I’m really curious about what’s wrong with my particular solution (I know it’s a pretty dumb and inefficient one..)

Original question:

Have the function LetterCountI(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: "Today, is the greatest day ever!" should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's. If there are no words with repeating letters return -1. Words will be separated by spaces.

My solution works most of the time. But if it seems the last word of the input isn’t valued by my code. For example, for “a bb ccc”, “bb” will be returned instead of “ccc”. But the funny thing here is if the string only contains one word, the result is correct. For example, “ccc” returns “ccc”.

Please tell me where I was wrong. Thank you in advance!

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


}       

回答1:


I think the problem is that you're placing the return statement inside your outermost loop. It should be inside your inner loop.

So you have to place the return statement within the inner loop.

Correct use of return

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



回答2:


You need to move the return word; statement outside of the loop to fix your version.

I also put together another take on the algorithm that relies on a few built in javascript methods like Array.map and Math.max, just for reference. I ran a few tests and it seems to be a few milliseconds faster, but not by much.

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



回答3:


Please find below the workable version of your code:

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



回答4:


Yet another solution in a more functional programming style:

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




回答5:


I recommend use regular expression: /a+/g to find a list of letter with a key word a.

My example :

var str = aa yyyyy bb cccc cc dd bbb;

Fist, find a list of different word :

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

Use regular expression for each word in list of different word :

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

>>>>["yyyyy"]

Here is full example: http://jsfiddle.net/sxro0sLq/4/



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

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