Return the first word with the greatest number of repeated letters

前端 未结 5 1159
慢半拍i
慢半拍i 2021-01-16 23:16

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

相关标签:
5条回答
  • 2021-01-16 23:34

    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

    0 讨论(0)
  • 2021-01-16 23:38

    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;
    }
    
    0 讨论(0)
  • 2021-01-16 23:50

    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/

    0 讨论(0)
  • 2021-01-16 23:56

    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;
    }
    
    0 讨论(0)
  • 2021-01-17 00:00

    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;
        }
      }
    } 
    
    0 讨论(0)
提交回复
热议问题