返回句子中最大数量的重复字符

Return greatest number of repeated characters in a sentence

本文关键字:字符 句子 最大数 返回      更新时间:2023-09-26

好吧,也许我的最后一个问题我不够清楚。

我想返回字符串中重复字符最多的单词。

所以下面的字符串:

There/'s a passage that I got memorized, seems appropriate for this situation: Ezekiel 25,17.

会返回["appropriate"].

但是,如果有多个单词具有相同数量的重复字符,我想将它们全部返回。 所以下面的字符串

Hello all from Boston

会返回["Hello", "all", "boston"]

这是我到目前为止的代码。此代码取自另一个堆栈溢出线程

function returnRepeatChar(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;
      }
    });
    
    //convert 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;
}
console.log(returnRepeatChar("There/'s a passage that I got memorized, seems appropiate for this situation: Ezekiel 25,17.")); //"appropriate"

对代码进行以下简单更改。

var word = "-1";

成为:

var word = [];

更新word的代码变为:

//if the current word has a higher repeat count than previous max, replace it 
if (currentMaxRepeatedCount > maxCount){
  maxCount = currentMaxRepeatedCount;
  word = [currentWord];
} else if (currentMaxRepeatedCount == maxCount) {
  // If it's the same as the max, add it to the list
  word.push(currentWord);
}

是的,你可以做到。 请尝试以下脚本。

function largest(arr){
        var sortArr = arr.sort(function(a,b){return b.length - a.length});
        return sortArr;
    }
    function returnRepeatChar(str){
       return largest(str.toLowerCase().split(" "));
    }
    //This function return the sorted of the given string
    var sorted = returnRepeatChar("There''s a passage that I got memorized, seems appropriate for this situation: Ezekiel 25,17.");
alert(sorted);