본문 바로가기

Algorithm/Programers - Java

[프로그래머스(Java)] 문자 개수 세기 / groupingBy

 

Level. 0

 

문제

알파벳 대소문자로만 이루어진 문자열 my_string이 주어질 때, my_string에서 'A'의 개수, my_string에서 'B'의 개수,..., my_string에서 'Z'의 개수, my_string에서 'a'의 개수, my_string에서 'b'의 개수,..., my_string에서 'z'의 개수를 순서대로 담은 길이 52의 정수 배열을 return 하는 solution 함수를 작성해 주세요.

* 제한사항
- 1 ≤ my_string의 길이 ≤ 1,000

 

풀이

class Solution {
    public int[] solution(String my_string) {
        int[] answer = new int[52];
        for(int i=0; i<my_string.length(); i++){
            char c = my_string.charAt(i);
            if (c <= 'Z')
                answer[c-'A'] += 1;
            else 
                answer[c-'a'+26] += 1;
        }
        return answer;
    }
}

 


다른 풀이

class Solution {
    public int[] solution(String my_string) {
        int[] answer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        for(char ch: my_string.toCharArray()) {
            answer[ch - 'A' - (Character.isLowerCase(ch)?6:0)]++;
        }
        return answer;
    }
}

 

mport java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Solution {
    public int[] solution(String my_string) {
        return IntStream.concat(IntStream.concat(my_string.chars(), IntStream.rangeClosed('A', 'Z')), IntStream.rangeClosed('a', 'z'))
                .mapToObj(Character::toString)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .values().stream()
                .mapToInt(i ->  i.intValue() - 1)
                .toArray();
    }
}

 

collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))

>> gourpingBy의 두 번째 인자에 Collectors.counting을 전달하면, 동일한 자료의 개수를 구할 수 있다. 

 


https://school.programmers.co.kr/learn/courses/30/lessons/181902?language=java 

 

프로그래머스

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

programmers.co.kr