본문 바로가기

ALGORITHM

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

 

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

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

programmers.co.kr

⏱소요 시간 - 20분

 

🔑해결 방법

 

String 클래스의 toLowerCase() / toUpperCase() / equalsIgnoreCase(str) 중에 하나를 골라 사용하면 된다.

 

대소문자를 통일시켜놓고, charAt(i)을 이용해 i의 값을 배열의 길이만큼 증가시키면서

p나 y가 존재하는지 체크하고 존재하면 cnt를 증가시키는 로직이다.

그리고 마지막에 두 cnt가 같은지 비교하면 된다.

 

 

🔎소스 코드

 

package step1;

// 문자열 내 p와 y의 개수
public class Ex15 {

	public static void main(String[] args) {
		
		System.out.println(solution("pPoooyY"));
		System.out.println(solution("Pyy"));
		System.out.println(solution("pppyy"));
		
	}
	
	public static boolean solution(String s) {
		
		boolean answer = true;
		
		s = s.toLowerCase();
	
		int pCnt = 0;
		int yCnt = 0;
		
		for(int i = 0; i < s.length(); i++) {
			
			if(s.charAt(i) == 'p') {
				pCnt++;
			} else if(s.charAt(i) == 'y') {
				yCnt++;
			}
			
		}
		
		if(pCnt != yCnt) {
			return false;
		} 
		
		return answer;
		
	}

}