Return the first word with the greatest number of repeated letters

前端 未结 5 1164
慢半拍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

提交回复
热议问题