본문 바로가기
Algorithm

[프로그래머스] 문자열 내 p와 y의 개수 (JS, Python)

by YGSEO 2021. 1. 29.
728x90

JS

솔루션을 검색해보기 전까지 시도했던 방법은

regex를 사용해서 string.match() 메서드로 찾고자 하는 단어를 포함하는 새로운 array의 length를 return 하는 방법이였는데, 이 경우에는 문제점이 찾고자 하는 단어가 없으면 return null 하기 때문에 null 값에 대한 조건이 추가되기 때문에 error-prone한 방식이라서 이 점을 유의해야겠다.

s.match(/p/g).length

 

찾은 답안은 아래

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

 

답안을 보면,

split 메서드를 사용하면서 쉽고 간편하게 해결하는 모습이다.

찾고자 하는 단어가 빈 문자열로 대체되면서 새로운 array가 만들어진다.

문제에서는 단어의 개수를 비교하는 것이기 때문에 위와 같은 코드로 해결이 되지만

function solution(s){
    console.log(s.toUpperCase().split("P"),s.toUpperCase().split("Y"))
    return true;
}

solution("Pyy"); //Pyy

// output ----
// [ '', 'YY' ] [ 'P', '', '' ]
// true

만약에 찾고자 하는 단어의 개수를 각각 return 하는 문제가 나온다면?

function solution(s){
    let p_cnt = 0
    let y_cnt = 0

    if (s.toUpperCase().match(/P/g) === null) {
      p_cnt = 0;
    } else {
      p_cnt = s.toUpperCase().match(/P/g).length;
    };
    if (s.toUpperCase().match(/Y/g) === null) {
      y_cnt = 0;
    } else {
      y_cnt = s.toUpperCase().match(/Y/g).length;
    };

    return [p_cnt, y_cnt];
}

// output
// [ 0, 2 ]

null을 처리해줘야 한다.


Python

def solution(s):
    s = s.lower()
    p_cnt = s.count('p')
    y_cnt = s.count('y')

    return p_cnt == y_cnt

파이썬 같은 경우 JS 와 다르게 count 메서드를 통해 char counting을 하는데 없으면 0을 리턴한다.

 

다른 사람의 풀이

from collections import Counter
def numPY(s):
    # 함수를 완성하세요
    c = Counter(s.lower())
    return c['y'] == c['p'] 

Count를 활용해서 key, value indexing을 통해 문제 해결.

728x90

댓글