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

문제설명 )

 

풀이Code )

import java.util.ArrayList;

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        char [] list = new char[s.length()];
        int pCnt = 0;
        int yCnt = 0;

        for (int i=0; i<s.length(); i++) {
            list[i] = s.charAt(i);
        }

        for (int i=0; i<s.length(); i++) {
            if (list[i] == 'y' || list[i] == 'Y') {
                yCnt++;
            }
            else if (list[i] == 'p' || list[i] == 'P') {
                pCnt++;
            }
        }

        if (yCnt == pCnt) {
            answer = true;
        }else{
            answer = false;
        }

        return answer;
    }
}

 

 

풀이법 )

1. s라는 문자열을 for문 사용하여 char타입으로 나누어 배열에 저장한다.

2. char타입으로 저장한 배열을 for문 사용하여 y또는 p일때 cnt를 증가 시켜준다.

3. cnt값을 비교 하여 같으면 true 다르면 false 를 리턴해준다.