코플릿 21번문제 (객체)

수민·2022년 11월 4일
0

코플릿

목록 보기
5/11

문제

문자열을 입력받아 가장 많이 반복되는 문자(letter)를 리턴해야 합니다.

주의 사항

-

띄어쓰기는 제외합니다.
가장 많이 반복되는 문자가 다수일 경우, 가장 먼저 해당 횟수에 도달한 문자를 리턴해야 합니다.
빈 문자열을 입력받은 경우, 빈 문자열을 리턴해야 합니다.

입출력 예시

	
let output = mostFrequentCharacter('apples not oranges');
console.log(output); // --> 'p'

output = mostFrequentCharacter('hello world');
console.log(output); // --> 'l'

output = mostFrequentCharacter('   ');
console.log(output); // --> ''

output = mostFrequentCharacter('');
console.log(output); // --> ''

output = mostFrequentCharacter('abba');
console.log(output); // --> 'b'
function mostFrequentCharacter(str) {


      // str공백제거 한값을 변수 replace에할당.
      // if/else() 구문을 이용하여 replace개수 카운트
      // 카운트 된 값이 max의 값보다 크다면 그 값을 max와 maxS에 할당.
    const replace=str.replace(/ /g,"");
	

    let result={};
    let max=0;
    let maxS="";

    for(let i=0; i<replace.length; i++){
      if(result[replace[i]]){
        result[replace[i]]++;
      }else{
        result[replace[i]]=1;
      }


      if(result[replace[i]]>max){
        max=result[replace[i]];
        maxS=replace[i];
      }

    }   
    return maxS;
}


🤘 String.replace() 메소드를 사용하여 str공백제거 한값을 변수 replace에 할당
🤘 if/else() 구문을 이용하여 replace개수 카운트
🤘 카운트 된 값이 max의 값보다 크다면 그 값을 max와 maxS에 할당.

profile
헬창목표

0개의 댓글