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

allnight5·2023년 3월 15일
0

프로그래머스

목록 보기
42/73

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

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

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

자바

class Solution {
    boolean solution(String s) {
        boolean answer = true; 
        int[] sum = new int[2];
        String[] alphabet = s.split("");
        for(String a:alphabet){
            if(a.equals("p") ||a.equals("P")){ 
                sum[0] += 1;
            }else if(a.equals("Y") ||a.equals("y")){
                sum[1] += 1;
            }
        } 
        return sum[0] == sum[1] ?true :false;
    }
}

자바 개선

class Solution {
    boolean solution(String s) {
        s = s.toLowerCase();
        int count = 0; 
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'p')
                count++;
            else if (s.charAt(i) == 'y')
                count--;
        }
        return count == 0 ?true :false;
    }
}

자바 짧지만 효율 나쁜지

class Solution {
    boolean solution(String s) {
        s = s.toUpperCase();

        return s.chars().filter( e -> 'P'== e).count() 
        == s.chars().filter( e -> 'Y'== e).count();
    }
}

파이썬 첫번째

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

파이썬 다른방식

from collections import Counter
def solution(s):
    check = Counter(s.lower())
    
    return check['p'] == check['y']

첫번째가 다른방식보다 빠르다.

profile
공부기록하기

0개의 댓글