Programmers Lv1 문자열 내 p와 y의 개수

이지수·2022년 4월 28일
0

코딩테스트

목록 보기
2/2

문제

문자열을 입력받아 p와 y의 갯수를 세고 두개가 같으면 true 다르면 false를 리턴 (대소문자 구분 없음)

정보

입출력

Inputoutput
pPoooyYtrue
Pyyfalse

구현

아이디어

  1. 대소문자 구분이 없음으로 대문자로 다 변환
  2. char[] 로 변환하여 순차검사
  3. 변수공간 줄이기 위해서 pCnt, tCnt 대신 cnt++, cnt-- 로 변수하나로 처리

소스코드

전체소스: https://github.com/lee-jisoo/algorithm-study/blob/master/src/com/ljs/study/programers/Programmers02.java

public class Programmers02 {

    public static void main(String args[]) {
        System.out.println(solution("pPoooyY"));
        System.out.println(solution("Pyy"));
    }

    public static boolean solution(String input) {
        int cnt = 0;

        for (char c : input.toUpperCase().toCharArray()) {
            if (c == 'P') cnt++;
            else if (c == 'Y') cnt--;
        }

        return cnt == 0;
    }

여담

너무 쉬웠나..

추천이 많았던 베스트 솔루션

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

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

베스트 솔루션이 스트림처리로 간결하긴 한데, 성능면에서 그닥 추천하고 싶지 않다. 댓글에서도 논란이 많긴 하지만 스트림 사용측면에서 재밌는 답안.

profile
공부합시다

0개의 댓글