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

2019. 3. 1. 17:10알고리즘문제/프로그래머스

문자열 내 p와 y의 개수


1. 문제

https://programmers.co.kr/learn/courses/30/lessons/12916


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




solution - 2) 소름돋게 짧은 다른 사람의 풀이 

1
2
3
4
5
6
7
class Solution {
    boolean solution(String s) {
        s = s.toUpperCase();
 
        return s.chars().filter( e -> 'P'== e).count() == s.chars().filter( e -> 'Y'== e).count();
    }
}
cs



solution - 1) 나의 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    boolean solution(String s) {
        boolean answer = true;
        s = s.toLowerCase();
        int pCount = 0;
        int yCount = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'p') {
                pCount++;
            } else if (s.charAt(i) == 'y') {
                yCount++;
            }
        }
 
        if (pCount == yCount) {
            answer = true;
        } else if (pCount != yCount) {
            answer = false;
        }
 
        return answer;
    }
}
cs