본문 바로가기
Algorithm/Programmers

[Programmers] Lv.0 / 문자 개수 세기 / Java

by unknownomad 2023. 11. 30.

문제

 

풀이

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

        int[] answer = new int[52];

        for(char ch : my_string.toCharArray()) {
            int idx = Character.isUpperCase(ch) ? (ch - 'A') : (ch - 'a' + 26);
            answer[idx]++;
        }
        return answer;
    }
}
class Solution {
    public int[] solution(String my_string) {
    
        int[] answer = new int[52];

        for(char ch : my_string.toCharArray()) {
            if(Character.isUpperCase(ch)) {
                answer[ch - 65]++;
            } else {
                answer[ch - 71]++;
            }
        }
        return answer;
    }
}
import 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();
    }
}

 

출처

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

댓글