본문 바로가기

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

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

 

https://school.programmers.co.kr/learn/courses/30/lessons/12916

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

해설 1 :  p와 y의 개수를 일일이 카운트

 

class Solution {
    boolean solution(String s) {
        // p와 y의 개수를 일일이 카운트 해주는 방법
        boolean answer = true;
        int pGetsu = 0;
        int yGetsu = 0;
        for(char c : s.toCharArray()){
            if(c == 'p' || c == 'P') pGetsu++;
            if(c == 'y' || c=='Y') yGetsu++;
        }
        
        if(pGetsu==0 && yGetsu==0) answer = true;
        if(pGetsu==yGetsu) answer = true;
        else answer = false;

        return answer;
    }
}

 

해설 2 :  문자를 모두 소문자로 바꾸어준 후 카운트

 

class Solution {
    boolean solution(String s) {
        // 문자를 모두 소문자로 바꾸어준 후 카운트
        String s2 = s.toLowerCase();
        int count = 0;
        for(char c : s2.toCharArray()) {
            if(c == 'p') count++;
            if(c == 'y') count--;
        }
        // p와 y의 개수가 같다면 변수 count는 0
        return count==0;
    }
}

 

해설 3 : replaceAll 메소드 사용

 

class Solution {
    boolean solution(String s) {
        // p or P, y or Y 아니라면 ""로 바꾼 후 문자열의 길이 비교
        int p = s.replaceAll("[^pP]", "").length();
        int y = s.replaceAll("[^yY]", "").length();
        
        return p==y;
    }
}