Answer the question
In order to leave comments, you need to log in
How to return the last element?
Hello. I'm solving algorithmic problems and I have a question.
Task:
Given a string, and it is necessary to find the most repeated character in it.
That is: "abcccss" => "c";
My implementation:
const maxChar = str => {
const charObj = {};
let max = 0;
let maxChar = '';
for (let char of str) {
if (charObj[char]) {
charObj[char]++;
} else {
charObj[char] = 1;
}
}
for (let char in charObj) {
if (charObj[char] > max) {
max = charObj[char];
maxChar = char;
}
}
console.log(charObj);
return maxChar;
};
maxChar('abccccsddasdadwqwf') => "c" // а должно "d"
Answer the question
In order to leave comments, you need to log in
Algorithmically, it is possible to calculate it in one pass of the loop
const maxChar = str => {
const charObj = {};
let max = {char:'', count:''};
let maxChar = '';
for (let char of str) {
if (charObj[char]) {
charObj[char]++;
} else {
charObj[char] = 1;
}
if ( charObj[char] >= max.count ) {
max.char = char
max.count = charObj[char]
}
}
return max.char;
};
console.log( maxChar('abccccsddasdadwqwf'))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question