본문 바로가기
코플릿 기록/JavaScript

객체 21번 (continue, break) ★★★★

by 뭉지야 2023. 1. 1.
728x90

#문제

문자열을 입력받아 가장 많이 반복되는 문자(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'

#풀이

반복문 돌리다가 공백이 나와서 건너뛴다. 
break : 공백나오면 반복문종료
continue: 공백나오면 이번횟수만 건너뛴다

 

if(str[i] === ' ') {
      continue;
      //공백이 나오면 건너뛴다는 의미이다.
if(!(str[i] in obj)) {
        obj[str[i]] = 0;
    }
    obj[str[i]] ++
    //여기까지가 b:1, a:3, n:2만들어져있다
mostCount = obj[str[i]]; //3
    mostChar = str[i]; //'a'

#정답

function mostFrequentCharacter(str) {
    
 let obj= {mostCount: 0, mostChar: ''};
 for(let i=0; i< str.length; i++){
 if(str[i] === ' '){
  continue;  //공백이 나오면 건너뛴다는의미
  }
  if(!(str[i] in obj)){
  obj[str[i]] = 0;
  }
  obj[str[i]]++;   //여기까지가 b:1 a:3 n:2 만들어져있다
if(obj[str[i]] > obj['mostCount']){
 obj['mostCount'] = obj[str[i]];
 obj['mostChar'] = str[i];
 }
 }
 return obj['mostChar'];
}
728x90

'코플릿 기록 > JavaScript' 카테고리의 다른 글

배열 6번 (split)  (0) 2023.01.02
객체 17번  (0) 2023.01.01
객체 18번  (0) 2023.01.01
객체 14번★★  (0) 2023.01.01
객체 12번 (속성의 개수)★★  (0) 2023.01.01