본문 바로가기
IT/Javascript

문자열 내 p 와 y 의 개수

by DOSGamer 2022. 7. 13.
반응형

문제

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

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

제한사항

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

풀이방향

  • 대소문자 구분없에기 위해서 toLowerCase 사용
  • 문자내에 P 개수
  • 문자내에 Y 개수
  • 기본이 True
  • PY 개수 틀리면 False

풀이

function comparePY(s) {
  var answer = true;
  let cntY = 0;
  let cntP = 0;
  var arr_s = s.toLowerCase().split("");
  for (let i = 0; i < arr_s.length; i++) {
    if (arr_s[i] === "y") {
      cntY++;
    } else if (arr_s[i] === "p") {
      cntP++;
    }
  }

  if (cntY !== cntP) {
    answer = false;
  }
  return answer;
}

console.log(comparePY("pPoooyY"));
console.log(comparePY("Pyy"));
console.log(comparePY("ab"));

export { comparePY };
import { comparePY } from "../src/comparePY";

describe('comparePY', () => {
  it('should return true if the number of "p" and "y" is the same', () => {
    expect(comparePY("pPoooyY")).toBe(true);
  });
  it('should return false if the number of "p" and "y" is the different', () => {
    expect(comparePY("Pyy")).toBe(false);
  });
  it('should return true if the number of "p" and "y" is zero', () => {  
      expect(comparePY("ab")).toBe(true);
  });
});

출처

다른 풀이

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


// 아래는 테스트로 출력해 보기 위한 코드입니다.
console.log( numPY("pPoooyY") )
console.log( numPY("Pyy") )
반응형

'IT > Javascript' 카테고리의 다른 글

문자열을 정수로 바꾸기  (0) 2022.07.14
비밀지도  (0) 2022.07.14
제일 작은 수 제거하기  (0) 2022.07.14
직사각형 별 찍기  (0) 2022.07.13
소수 찾기  (0) 2022.07.13
자연수 뒤집어 배열로 만들기  (0) 2022.07.13
문자열 내 마음대로 정렬하기  (0) 2022.07.13
최소직사각형  (0) 2022.07.13