본문 바로가기
(문제풀이)

프로그래머스(JAVA) : 문자열 내 p와 y의 개수

by cogito-new 2022. 9. 14.

Stream 방식으로 풀이

import java.util.Arrays;

class Solution {
    boolean solution(String s) {    
        String[] arrayString = s.split("");
        long countP = Arrays.stream(arrayString)
                .map(String::toUpperCase)
                .filter(y -> y.equals("P"))
                .count();
        long countY = Arrays.stream(arrayString)
                .map(String::toUpperCase)
                .filter(z -> z.equals("Y"))
                .count();
        if(countP == countY){
            return true;
        } else {
            return false;
        }
    }
}

 

- 다른 사람의 풀이

class Solution {
    boolean solution(String x) {
        x = x.toUpperCase();
        
        // chars() 메소드는 java.lang.String 내의 메소드로, IntStream을 반환한다.
        // character 타입은 아스키코드값으로 비교가 가능하므로 
        // 만들어준 intStream 에서 filter로 P, Y 와 아스키 코드값 비교를 하고
        // 일치하면 true, 불일치하면 false 반환한다.
        
        return x.chars().filter(y -> y=='P').count() == x.chars().filter(z -> z=='Y').count();
    }
}

 

반복문 사용해서 풀이

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        String[] s1 = new String[s.length()];
		s1 = s.split("");
		int countX = 0;
		int countY = 0;
		for(int i = 0; i<s.length(); i++) {
			if(s1[i].equals("p") || s1[i].equals("P")) {
				countX ++;
			} else if(s1[i].equals("y") || s1[i].equals("Y")) {
				countY ++;
			}
		}
		if(countX == countY) {
			answer = true;
		} else if(countX ==0 && countY ==0) {
			answer = true;
		} else {
			answer = false;
		}


        return answer;
    }
}
반응형