프로그래머스 Level1-8 | 문자열 내 p와 y의 개수

yuriyaam·2021년 1월 27일
0
post-thumbnail

람다식 공부를 위해 여기부터 보고 오자!
람다식(Rambda) 개념 및 사용법


문제

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

입출력 예

문자열 s가 pPoooyY면 true를 return하고 Pyy라면 false를 return합니다.

코드

static boolean solution(String s) {
//	boolean answer = true;
	
	s = s.toLowerCase();
	String[] str = s.split("");

	int count = 0;
	for(int i = 0; i < str.length; i++) {
		if(str[i].equals("p"))
				count++;
		else if(str[i].equals("y"))
			count--;
	}
		
//	answer = (count == 0) ? true : false;
		
	return count == 0;
}

새로운 문법을 배웠다.
boolean answer 변수를 사용하여 메모리를 차지할 필요 없이,
return count ==0;을 하면 true or false를 리턴해준다.

더욱 간결한 코드

class Solution {
    boolean solution(String s) {
        s = s.toUpperCase();

        return s.chars().filter( e -> 'P'== e).count() == s.chars().filter( e -> 'Y'== e).count();
    }
}

0개의 댓글