풀이 

영문자 ascii값을 idx로 한 배열을 만들고 값에다가 갯수를 저장해줬다. 

 

p와 y의 idx 값 구하기

 public static void main(String[] args) {
        int P = 'P' - 'A';
        int p = 'p' - 'A';
        int y = 'y' - 'A';
        int Y = 'Y' - 'A';

        System.out.println("P = " + P);
        System.out.println("p = " + p);
        System.out.println("Y = " + Y);
        System.out.println("y = " + y);

//        P = 15
//        p = 47
//        Y = 24
//        y = 56

    }

 

public static boolean solution(String s) {
    // 영문자 char의 ascii값을 index로하는 길이가 58인 int 배열 생성
    int[] arr = new int[58];

    // s 를 하나씩 읽어서 ascii 값이 index인 자리에 값 증가
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        arr[c - 'A']++;
    }

    // p의 개수와 y의 개수 구하기
    int p = arr[15] + arr[47];
    int y = arr[24] + arr[56];

    if (p == y) return true;
    else
        return false;
}

 

 

다른 풀이

s의 대문자를 소문자로 바꾼후 한글자씩 비교 

변수는 count 하나만 둬서 모든 char 비교후

값이 0이 나오면 p와 y값이 동일하므로 true리턴

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--;
        }

        if (count == 0)
            return true;
        else
            return false;
    }
}

+ Recent posts