Just Do IT!

[프로그래머스 level 0] 문자 개수 세기 - 181902 (Java) 본문

코딩테스트 준비/프로그래머스

[프로그래머스 level 0] 문자 개수 세기 - 181902 (Java)

MOON달 2024. 11. 24. 17:38
728x90
반응형

문제 설명

알파벳 대소문자로만 이루어진 문자열 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

입출력 예
my_string answer
"Programmers" [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0]

 

 

 

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 >= 'A' && c <= 'Z') {
                answer[c - 'A']++;
            } else if (c >= 'a' && c <= 'z') {
                answer[26 + c - 'a']++;
            }
        }
        
        return answer;
    }
}

 

  1. 52개로 배열 설정 (대문자+소문자)
  2. c - 'A' : 대문자
  3. 26 + c - 'a' : 소문자
728x90