Programmers/프로그래머스-문자 개수 세기-Python/Go/Java

cosmos·2023년 6월 17일
0
post-thumbnail

문제

Python Code

from typing import List

def solution(my_string: str) -> List[str]:
    alpha_dict = {chr(x): 0 for x in range(ord('A'), ord('Z')+1)}
    alpha_dict.update({chr(x): 0 for x in range(ord('a'), ord('z')+1)})

    
    for string in my_string:
        alpha_dict[string] += 1
    
    return list(alpha_dict.values())

Go Code

func solution(myString string) []int {
	counts := make([]int, 52)

	for _, char := range myString {
		if char >= 'A' && char <= 'Z' {
			counts[char-'A']++
		} else if char >= 'a' && char <= 'z' {
			counts[char-'a'+26]++
		}
	}

	return counts
}

Java Code

import java.util.Arrays;

class Solution {
    public int[] solution(String my_string) {
        int[] counts = new int[52]; // 알파벳 개수를 저장할 배열 초기화
        
        for (char c : my_string.toCharArray()) {
            if (c >= 'A' && c <= 'Z') { // 대문자인 경우
                int index = c - 'A'; // 알파벳의 인덱스 계산
                counts[index]++; // 개수 증가
            } else if (c >= 'a' && c <= 'z') { // 소문자인 경우
                int index = c - 'a' + 26; // 알파벳의 인덱스 계산
                counts[index]++; // 개수 증가
            }
        }
        
        return counts;
    }
}

결과

문제출처 & 깃허브

Programmers
Github

0개의 댓글