본문 바로가기

프로그래머스/LEVEL 1

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

문제

 

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

 

코드

class Solution {
    boolean solution(String s) {
		boolean result = true;
		// toLowerCase() 소문자로 변환 메서드
		String lower_s = s.toLowerCase();
		int pCount = 0;
		int yCount = 0;

		pCount = countChar(lower_s, 'p');
		yCount = countChar(lower_s, 'y');

		result = pCount == yCount ? true : false;
		
		return result;
    }
    
    // 해당 문자열 포함갯수 구하기
    int countChar(String s, char ch) {
		int count = 0;

		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == ch) {
				count++;
			}
		}

		return count;
	}
}