[Lv.1] 문자열 내 p와 y의 개수

01수정·2023년 11월 1일
0

문제


풀이

function solution(s){
    let count_p = 0;
    let count_y = 0;
    
    for (let i=0; i<s.length; i++) {
        if (s[i] === 'p' || s[i] === 'P') {
            count_p++;
        } else if (s[i] === 'y' || s[i] === 'Y') {
            count_y++;
        }
    }
    
    if (count_p === count_y) {
        return true;
    } else {
        return false;
    }
}

다른 풀이

function numPY(s){
  //함수를 완성하세요
    return s.toUpperCase().split("P").length === s.toUpperCase().split("Y").length;
}
function numPY(s){
  return s.match(/p/ig).length == s.match(/y/ig).length
}
function solution(s){
    return [...s.toLowerCase()].reduce((acc, cur) => {
        if(cur ==='p') return acc + 1;
        else if(cur ==='y') return acc - 1;
        return acc;
    }, 0) ? false : true;
}
profile
새싹 FE 개발자

0개의 댓글