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

선예원·2021년 10월 14일
0
post-thumbnail

문제 설명

  • 대문자와 소문자가 섞여있는 문자열 s가 주어져. s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return.
  • 'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴.
  • 단, 개수를 비교할 때 대문자와 소문자는 구별X.

풀이

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        char ch = ' ';
        int cnt = 0;
        for(int i = 0; i < s.length(); i ++){
            ch = s.charAt(i);
            if (ch == 'p' || ch == 'P'){
                cnt ++;
            }
            else if (ch == 'y' || ch == 'Y'){
                cnt --;
            }
        }

        if (cnt !=0)
           answer = false; 
        return answer;
    }
}

다른 사람의 풀이

_-Stream이용, 람다식 활용

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

        return s.chars().filter( e -> 'P'== e).count() == s.chars().filter( e -> 'Y'== e).count();
    }
}
  • filter는 요소를 특징으로 걸러낼 수 있음.

0개의 댓글

관련 채용 정보