Little Jay

[C++] 백준 10808번 - 알파벳 개수 본문

알고리즘/BOJ

[C++] 백준 10808번 - 알파벳 개수

Jay, Lee 2021. 9. 25. 14:38

C++ Array 연습 기초

 

첫 번째는 무지성 string으로 푸는 방법이다.

O(n^2)로 간단하게 풀 수 있는 문제이다.

처음 for문은 char 알파벳이 돈다

이제 다음 for문은 입력된 string 안에있는 char과

처음 for문의 알페벳이 몇개나 일치하는지 확인한다.

 

#include <iostream>
#include <string>
using namespace std;

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0);

	string s;
	cin >> s;

	for (char i = 'a'; i <= 'z'; i++) {
		int count = 0;
		for (auto c : s) {
			count += (i == c);
		}
		cout << count << ' ';
	}
	cout << '\n';
	

	return 0;
}

 

두 번째는 메모리 관리를 위한 Array를 활용한 방법이다.

 

0으로 초기화된 int형 array를 하나 만들어준다. 이때 array는 알파벳 숫자만큼의 사이즈이다.

for 문을 한번 돌면서 알파벳 순서에 맞는 자리에 가산 연산을 해준다.

그리고 다른 for문으로 출력해주면 끝.

사실 문제가 너무 간단해서 걸리는 시간이랑 메모리 사용량에는 큰 차이가 없는 것 같다.

#include <iostream>
#include <string>
using namespace std;

int alphabet[26]{ 0, };

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0);

	string s;
	cin >> s;

	for (auto c : s) {
		alphabet[c - 'a']++;
	}

	for (int i = 0; i < 26; i++) {
		cout << alphabet[i] << ' ';
	}
	cout << '\n';
	

	return 0;
}

 

'알고리즘 > BOJ' 카테고리의 다른 글

[C++] 백준 7875번 - Brackets  (0) 2021.09.26
[C++] 백준 1712번 - 손익분기점  (0) 2021.09.25
[C++] 백준 1010 - 다리놓기  (0) 2021.09.20
[C++] 백준 16768번 - Mooyo Mooyo  (0) 2021.09.20
[C++]백준 14502 - 연구소  (0) 2021.09.19
Comments