코딩테스트/프로그래머스

[프로그래머스] [Level 1] 문자열 내 p와 y의 개수

박소민 2022. 2. 23. 18:26
문제) 문자열 내 p와 y의 개수
 

코딩테스트 연습 - 문자열 내 p와 y의 개수

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

programmers.co.kr

 

  • 내 풀이
def solution(s):
    p_ls=[i for i in s if i=='p' or i=='P']
    y_ls=[j for j in s if j=='y' or j=='Y']
    if len(p_ls)==len(y_ls):
        return True
    else:
        return False

 

 

  • 다른 사람 풀이

- count 함수 사용→ 시간 단축

def solution(s):
    return s.count('P')+s.count('p')==s.count('Y')+s.count('y')

- 모두 소문자로 바꾸고 count함수 사용하기도 함

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