所以我正在学习如何返回字符串中最常见的字符。我知道怎么做,如果只有一个角色出现最多e.i," a"在" javascript"出现两次,其余字符只出现一次。但是如果字符串是“javascript prototype'”,那么最常出现的两个字符是" p"和" t"。我正在使用_.invert()来获取字母最多出现的数字的值,而且我是因为" p"和" t"两者都等于3然后我可以归还它们。我期待输出
"p t"
// Return the character that is most common in a string
// ex. maxCharacter('javascript') == 'a'
// Return multiple characters that are most common in a string
// ex. maxCharacter('javascript prototype') == 'p t'
function maxCharacter(str) {
const charMap = {};
let maxNum = 0;
let maxChar = '';
str.replace(/\s/gi, '').split('').forEach(function(char){
if(charMap[char]){
charMap[char]++;
} else {
charMap[char] = 1;
}
});
for(let char in charMap){
if(charMap[char] > maxNum) {
maxNum = charMap[char];
maxChar = (_.invert(charMap))[maxNum];
}
}
return maxChar;
}
// Call Function
const output = maxCharacter('javascript prototype');
console.log(output);

答案 0 :(得分:2)
charMap
function maxCharacter(str) {
const charMap = {};
str.replace(/\s/gi, '').split('').forEach(function(char){
if(charMap[char]){
charMap[char]++;
} else {
charMap[char] = 1;
}
});
const max = Math.max(...Object.values(charMap));
return Object.keys(charMap)
.filter((c) => charMap[c] === max)
.join(' ');
}
console.log(maxCharacter('javascript')); // a
console.log(maxCharacter('javascript prototype')); // p t
spreading Object.values()
查找Math.max()
中的最大数字。然后使用Array.filter()
获取具有最大值的键,并使用空格连接它们:
class TimedOutFilter(logging.Filter):
def filter(self, record):
if "Error while getting Updates: Timed out" in record.getMessage():
return False
return True # <==== Added this line only