프로그래머스 연습문제 '문자열 내 p와 y의 개수'

dowon kim·2023년 5월 23일
0

알고리즘 풀이

목록 보기
1/3

문제 설명
대문자와 소문자가 섞여있는 문자열 s가 주어집니다. s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return 하는 solution를 완성하세요. 'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴합니다. 단, 개수를 비교할 때 대문자와 소문자는 구별하지 않습니다.

예를 들어 s가 "pPoooyY"면 true를 return하고 "Pyy"라면 false를 return합니다.

제한사항
문자열 s의 길이 : 50 이하의 자연수
문자열 s는 알파벳으로만 이루어져 있습니다.

내 답안

function solution(s){
    let cntp = 0;
    let cnty = 0;
    
    for (let i = 0; i < s.length; i++) {
    let ch = s.charAt(i);

    if (ch === 'p' || ch === 'P') cntp++;
    else if (ch === 'y' || ch === 'Y') cnty++;
  }

  if (cntp === cnty) return true;
  else return false;
}

모범답안

function solution(s){
    return s.toUpperCase().split("P").length === s.toUpperCase().split("Y").length;
}

후기

ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ
좋게말하면 진짜 직관적으로 풀었고 , 나쁘게 말하자면 진짜 무식하게 풀었구나 싶었다.

profile
The pain is so persistent that it is like a snail, and the joy is so short that it is like a rabbit's tail running through the fields of autumn

0개의 댓글