Skip to content

Instantly share code, notes, and snippets.

@hoanbka
Created October 28, 2017 10:45
Show Gist options
  • Save hoanbka/3fa7dc2a749e07424854338dacae3a0d to your computer and use it in GitHub Desktop.
Save hoanbka/3fa7dc2a749e07424854338dacae3a0d to your computer and use it in GitHub Desktop.
Find max occurence of chars in a string
function findMaxOccurence(str) {
var map = new Map();
var max = 0;
for (var i = 0; i < str.length; i++) {
if (map.has(str.charAt(i))) {
map.set(str.charAt(i), map.get(str.charAt(i)) + 1);
} else {
map.set(str.charAt(i), 1);
}
max = max < map.get(str.charAt(i)) ? map.get(str.charAt(i)) : max;
}
var result = [];
for (var i = 0; i <= map.size; i++) {
if (map.get(str.charAt(i)) === max && result.indexOf(str.charAt(i)) < 0) {
result.push(str.charAt(i));
}
}
/*var result = [];
var arrKey = Array.from(map.keys());
for (var i = 0; i < arrKey.length; i++) {
if (map.get(arrKey[i]) == max) result.push(arrKey[i]);
}
}*/
return result;
}
function findMaxOccurenceUsingObject(str) {
var arr = str.split('');
var map = {};
var max = 0;
for (var i in arr) {
map[arr[i]] = map[arr[i]] === undefined ? 1 : map[arr[i]] + 1;
max = map[arr[i]] > max ? map[arr[i]] : max;
}
var output = [];
for (var i in map) {
if (map[i] === max) output.push(i);
}
return output;
}
console.log(findMaxOccurence('helloaa'));
console.log(findMaxOccurenceUsingObject('helloaa'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment