[Programmers] #181902 - 문자 개수 세기 [Java][C++][Python]
알파벳 대소문자로 이루어진 문자열에서 각 글자의 출현 횟수를 길이 52 배열로 반환하는 워밍업 문제.
[Programmers] #181902 - 문자 개수 세기 [Java][C++][Python]
1. 아이디어
길이 52의 카운트 배열을 두고 문자열을 한 번 순회하면서 각 문자에 대응하는 칸을 1씩 증가시킨다. 대문자 'A'~'Z'를 0~25번, 소문자 'a'~'z'를 26~51번에 대응시키면 대문자는 c - 'A', 소문자는 c - 'a' + 26으로 인덱스를 계산할 수 있다. 순회가 끝나면 이 배열이 그대로 정답이다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = my_string의 길이. 카운트 배열은 길이 52로 고정되므로 추가 공간은 상수이다)
3. 코드
풀이 [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):
counter = Counter(my_string)
return [counter[c] for c in string.ascii_uppercase + string.ascii_lowercase]
Counter(my_string)가 한 번의 순회로 문자별 개수를 센다. string.ascii_uppercase + string.ascii_lowercase는 'A'~'Z' 다음에 'a'~'z'가 오는 52글자 문자열이므로, 이 순서대로 각 문자를 counter에서 조회해 리스트로 만들면 요구되는 배열이 된다. Counter는 없는 키를 조회하면 0을 돌려주므로 한 번도 등장하지 않은 문자도 자연히 0으로 채워진다.
This post is licensed under CC BY 4.0 by the author.