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

김소정·2022년 3월 2일
0

프로그래머스

목록 보기
24/35

❔ 문제

❗ 내 풀이

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        
        String[] arr = s.toLowerCase().split("");		// 대,소문자 소문자로 통일시키기
        
        int pcnt = 0;
        int ycnt = 0;
        for(int i = 0; i < arr.length; i++){
            if(arr[i].equals("p")){
                pcnt++;
            }else if(arr[i].equals("y")){
                ycnt++;
            }
        }
                     
        if(pcnt == ycnt){
            answer = true;
        }else{
            answer = false;
        }
                    

        return answer;
    }
}

🚩참고 (다른 풀이)


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

        return s.chars().filter( e -> 'P'== e).count() == s.chars().filter( e -> 'Y'== e).count();		// 간결하다... 그런데 성능효율성은 떨어진다고 한다.
    }
}

2.
class Solution {
    boolean solution(String s) {
        s = s.toLowerCase();
        int count = 0;		//카운트 변수를 한개만 쓰는 것도 방법!

        for (int i = 0; i < s.length(); i++) {

            if (s.charAt(i) == 'p')
                count++;
            else if (s.charAt(i) == 'y')
                count--;
        }

        if (count == 0)
            return true;
        else
            return false;
    }
}

📝 정리

💬 카운트 변수 한개만 사용하는 것도 고려해보기

✔ String api 확인(equalsIgnoreCase)


profile
개발자 가보자고

0개의 댓글

관련 채용 정보