ΠŸΠ΅Ρ€Π΅ΠΉΡ‚ΠΈ ΠΊ основному содСрТимому

πŸ“„ Поиск самого частого символа

ОписаниС задачи​

Π‘ΠΎΠ·Π΄Π°ΠΉΡ‚Π΅ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ, которая ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π΅Ρ‚ строку ΠΈ Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ символ, Π²ΡΡ‚Ρ€Π΅Ρ‡Π°ΡŽΡ‰ΠΈΠΉΡΡ Ρ‡Π°Ρ‰Π΅ всСго.

1. ВСрсия Π½Π° JavaScript​

function findMostFrequentChar(str) {
// init object to store char and count
const charCount = {};

// init record of max count and char variable
let maxCount = 0;
let maxChar = '';

// loop through string
for (let char of str) {
// if char is not in object, set count to 0
if (!charCount[char]) {
charCount[char] = 0;
}

// increment this char count + 1
charCount[char]++;

// if this char count is greater than max count
// update max count and max char
if (charCount[char] > maxCount) {
maxCount = charCount[char];
maxChar = char;
}
}

// return max char
return maxChar;
}

console.log(findMostFrequentChar('abcccccccd')); // c