[프로그래머스] 51. 문자 개수 세기

최재원's avatar
Apr 12, 2025
[프로그래머스] 51. 문자 개수 세기
💡

문제 설명

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

입출력 예 설명

입출력 예 #1
  • 예제 1번의 my_string에서 'P'가 1개, 'a'가 1개, 'e'가 1개, 'g'가 1개, 'm'이 2개, 'o'가 1개, 'r'가 3개, 's'가 1개 있으므로 [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]를 return 합니다.
 

코드

class Solution { public int[] solution(String my_string) { int[] answer = new int[52]; char[] checkList = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; for(int i = 0; i < my_string.length(); i++) { for(int ii = 0; ii < checkList.length; ii++) { if(my_string.charAt(i) == checkList[ii]) { answer[ii]++; } } } return answer; } }
notion image

char → int 묵시적 형변환 사용

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') answer[c - 'a' + 26]++; else answer[c - 'A']++; } return answer; } }
notion image
Share article

jjack1