코딩 테스트

(Java) 문자열 p와 y의 개수

로승리 2021. 11. 13. 06:49

p와 y의 변수를 따로 설정해서 푸는게 마음에 안들었는데

다른 분 코드를 보니 count 변수 하나로 더하거나 빼서 답안을 만들었다.

유연하게 생각하면 저런 답이 나오는것 같다.


최종코드

class Solution {
    boolean solution(String s) {
        boolean answer = true;

        int pc = 0;
        int yc = 0;

        for(int i=0; i<s.length(); i++) {
            s = s.toLowerCase();
            char ch = s.charAt(i);
            if(ch == 'p') {
                pc++;
            } else if(ch == 'y') {
                yc++;
            }
        }
        if(pc == yc) {
            answer = true;
        } else {
            answer = false;
        }

        return answer;
    }
}

 

다른 분 코드

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