본문 바로가기

Java/프로그래머스

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

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

 

 

정답 

 

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        
        s = s.toLowerCase(); //소문자로 변경 
        int pcnt = 0;
        int ycnt = 0;
        
        for(int i=0; i<s.length(); i++)
        {
            char cur = s.charAt(i);
            
            if(cur == 'y')
            {
                ycnt++;
            }
            else if(cur=='p')
            {
                pcnt++;
            }
        }
        
        answer = (ycnt==pcnt)?true:false;

        return answer;
    }
}

 

 

 

다른 사람의 풀이 

 

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;
    }