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
'Algorithm > Programers - Java' 카테고리의 다른 글
[프로그래머스(Java)] 문자열 계산하기 / split (0) | 2023.08.26 |
---|---|
[프로그래머스(Java)] 영어가 싫어요 / map, replaceAll (0) | 2023.08.26 |
[프로그래머스(Java)] 잘라서 배열로 저장하기 (0) | 2023.08.26 |
[프로그래머스(Java)] qr code / Stream (0) | 2023.08.20 |
[프로그래머스(Java)] 커피 심부름 (0) | 2023.08.20 |