[Programmers] #181902 - 문자 개수 세기 [Java][C++][Python]
[Programmers] #181902 - 문자 개수 세기 [Java][C++][Python]
1. 아이디어
대문자 A~Z와 소문자 a~z의 등장 횟수를 이 순서대로 담은 배열을 만드는 문제다. 앞 26칸이 대문자, 뒤 26칸이 소문자 몫이므로, 대문자는 A를 0으로 센 알파벳 순서가 곧 인덱스이고, 소문자는 같은 순서에 26을 더한 인덱스에 집계한다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int[] solution(String my_string) {
int[] cnt = new int[52];
for (char c : my_string.toCharArray()) {
if (Character.isUpperCase(c)) {
cnt[c - 'A']++;
} else {
cnt[c - 'a' + 26]++;
}
}
return cnt;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(string my_string) {
vector<int> cnt(52);
for (char c : my_string) {
if (isupper(c)) {
cnt[c - 'A']++;
} else {
cnt[c - 'a' + 26]++;
}
}
return cnt;
}
1
2
3
4
5
6
7
import string
from collections import Counter
def solution(my_string):
cnt = Counter(my_string)
return [cnt[c] for c in string.ascii_uppercase + string.ascii_lowercase]
Counter는 세지 않은 키를 조회하면 예외 대신 0을 돌려주므로 등장하지 않은 알파벳도 그대로 꺼냈다.
This post is licensed under CC BY 4.0 by the author.