Created
August 16, 2022 07:27
-
-
Save marcobiedermann/e47afa4c18d13ab3b98f366139abefd7 to your computer and use it in GitHub Desktop.
Given a string, return the character that is most commonly used in the string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function maxChar(str: string): string { | |
const map = new Map<string, number>(); | |
let maxValue; | |
let maxCount = 0; | |
for (let char of str) { | |
const newCount = (map.get(char) || 0) + 1; | |
if (newCount > maxCount) { | |
maxValue = char; | |
maxCount = newCount; | |
} | |
map.set(char, newCount); | |
} | |
return maxValue; | |
} | |
maxChar("abcccccccd"); // c | |
maxChar("apple 1231111"); // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JS Edition: