입력받은 문자열의 문자의 등장수에 따른 가장 많이 등장한 문자를 리턴.
- sort()를 사용해서 했는데, 먼저 등장수를 가장 많이 채운 문자를 구분못함.
function mostFrequentCharacter(str) {
let charArr = [];
let trim_str = str.replace(/(\s*)/g,'');
if(!trim_str.length) return '';
charArr.push(new Object({char: trim_str[0], cnt: 1}));
for(let i=1; i<trim_str.length; i++) {
for(let j=0; j<charArr.length; j++) {
console.log(charArr[j])
if(charArr[j].char === trim_str[i]){
charArr[j].cnt++;
}
}
charArr.push(new Object({char: trim_str[i], cnt: 1}));
}
charArr.sort((a,b) => {
return a.cnt - b.cnt;
})
return charArr[0].char;
}
- 따로 체크하는 배열 두고, sort()는 필요없으니 삭제.
function mostFrequentCharacter(str) {
let charArr = [];
let countChar = { char:"", count:0};
let trim_str = str.replace(/(\s*)/g,'');
if(!trim_str.length) return '';
charArr.push(new Object({char: trim_str[0], cnt: 1}));
countChar.char = trim_str[0];
countChar.cnt = 1;
for(let i=1; i<trim_str.length; i++) {
for(let j=0; j<charArr.length; j++) {
if(charArr[j].char === trim_str[i]){
charArr[j].cnt++;
if(countChar.cnt < charArr[j].cnt) {
countChar.char = charArr[j].char;
countChar.cnt = charArr[j].cnt;
}
}
}
charArr.push(new Object({char: trim_str[i], cnt: 1}));
}
return countChar.char;
}