끄적끄적 코딩일지

[Programmers]문자열 내 p와 y의 개수(난이도:★★★) 본문

알고리즘

[Programmers]문자열 내 p와 y의 개수(난이도:★★★)

BaekGyuHyeon 2022. 5. 16. 18:59

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

 

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

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

programmers.co.kr

import java.util.Arrays;
class Solution {
    boolean solution(String s) {
        return solutionA(s);
    }
    // 솔루션 A
    public boolean solutionA(String s){
        String tmp = toUpperCase(s);
        int countP = getCount(tmp,'P');
        int countY = getCount(tmp,'Y');
        if(countP == 0 && countY == 0)
            return true;
        else
            return countP == countY; 
    }
    // 솔루션 B
    // Replace 사용
    // 전체 길이에서 p,y각각 replace한값을 빼면 p와 y의 개수를 알 수 있다.
    public boolean solutionB(String s){
        int totalLen = s.length();
        String tmp = s.toUpperCase();
        int countP = totalLen - tmp.replace("P","").length();
        int countY = totalLen - s.toUpperCase().replace("Y","").length();
        if(countP == 0 && countY == 0)
            return true;
        else
            return countP == countY; 
   
    }
    
    // count 구현
    public int getCount(String a,char b) {
    	char[] arr = a.toCharArray();
    	int count = 0;
    	for(int i = 0; i < arr.length; i++) {
    		if(arr[i] == b)
    			count++;
    	}
    	return count;
    }
    // toUpperCase 구현
    public String toUpperCase(String c) {
    	char[] arr = c.toCharArray();
    	for(int i = 0; i < arr.length; i++) {
    		if(arr[i] >= 97 && arr[i] <= 122 ) {
    			arr[i] = (char) (arr[i] - 32);
    		}
    	}
    	return new String(arr);
    }
}