본문 바로가기
알고리즘

[프로그래머스/코딩 테스트 연습] 문자열 연습하기-문자열 내 p와 y의 개수 (javascript)

by 지 요니 2023. 4. 6.

문제 설명

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

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

 

제한 사항

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

입출력 예

s answer
"pPoooyY" true
"Pyy" false

나의 풀이   

=>모든 문자열 하나씩 비교하는 방법 사용, 대소문자 통일 시킬 생각을 못했다. 아직 함수를 잘 활용 못하는듯

function solution(s){
    var answer = true;

// p,y 개수 세는 변수
    var count_y=0;
    var count_p=0;
    
    for(var i=0;i<s.length;i++){
        if(s[i]==='p'||s[i]==='P')
            count_p++;
        if(s[i]==='y'||s[i]==='Y')
            count_y++;
    }
    if(count_y===count_p || (count_y===0 && count_p===0)){
        answer=true;
    }else if(count_y!==count_p){
        answer=false;
    }
    return answer;
}

다른사람 풀이

function numPY(s){
  //함수를 완성하세요
    return s.toUpperCase().split("P").length === s.toUpperCase().split("Y").length;
}

// s = "pPoooyY";
// s.toUpperCase().split("P") => ["P", "P", "OOOYY"]
// s.toUpperCase().split("Y") => ["PPOOO", "Y" "Y"]

String.prototype.toLowerCase() => 모든 문자 소문자로 바꿈

String.prototype.toUpperCase() => 모든 문자 대문자로 바꿈

 

String.prototype.split()

split()	
split(separator)		// separator: 분할이 발생할 위치
split(separator, limit)	// limit : 배열에 포함될 문자열의 수를 지정

예시

const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' '); // space(띄어쓰기) 기준으로 분할
console.log(words[3]); 	// fox

const chars = str.spit('') // 모든 단어 + 공백 불할
console.log(char[8]);	// k

const strCopy = str.split();	// 배열로 바꾼 뒤 출력(분할 x)
console.log(strCopy);	// ["The quick brown fox jumps over the lazy dog."]

댓글