-
[ 10808 ] 알파벳 개수 - array, vector알고리즘/BOJ 2021. 7. 26. 20:33
< array, vector > - < solve등급 >
[ 10808 ]
알파벳 개수
알파벳 소문자로만 이루어진 단어 S가 주어진다. 각 알파벳이 단어에 몇 개가 포함되어 있는지 구하는 프로그램을 작성하시오.
:: 입력
첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.
:: 출력
단어에 포함되어 있는 a의 개수, b의 개수, …, z의 개수를 공백으로 구분해서 출력한다.
- try 1
: 알파벳 개수를 배열에 저장하려고 했는데 ,
인덱스를 계산하는 방법이 잘못된 듯 !
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define endl "\n" int alpa[26] = { 0, }; int main() { char word[100]; cin >> word; for (int i = 0; i < 100; i++) { char p = word[i]; int indx = p - 'a'; alpa[indx]++; } for (int i = 0; i < 26; i++) { printf("%d ", alpa[i]); } return 0; }
아이디어
인덱스 계산할 때 'a' 를 빼는 게 아니라 97을 빼줘야함
char 배열을 굳이 초기화하지 않고 널문자( '\0' )가 나오기 전까지 반복문을 돌려주는 방법을 사용함
정답 코드
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define endl "\n" int alpa[26] = { 0, }; int main() { char word[101] = {' ', }; cin >> word; for (int i = 0; i < 101; i++) { int p = word[i]; if (p == ' ') { break; } int indx = p - 97; alpa[indx]++; } for (int i = 0; i < 26; i++) { printf("%d ", alpa[i]); } return 0; }
인덱스 계산하는 법을 바꿈 첫트에서 틀렸던 이유는 저거 때문인 듯
+
반복문을 무의미하게 많이 돌지 않도록
배열을 공백으로 초기화 한 다음에
단어를 입력받고
반복문을 돌다가 공백이 나오면 탈출하게 함
다른 정답 코드
#include<stdio.h> int main(void) { char a[101]; int b[26]={0}; scanf("%s", a); int i=0; while(a[i]!='\0') { b[a[i]-97]++; i++; } for(int i=0; i<26; i++) printf("%d ", b[i]); }
'알고리즘 > BOJ' 카테고리의 다른 글
[ 11328 ] Strfry - array, vector (0) 2021.07.26 [ 1919 ] 에너그램 만들기 - array, vector (0) 2021.07.26 [ 10807 ] 개수 세기 - array, vector (0) 2021.07.26 [ 11024 ] 더하기 4 - 입출력 (0) 2021.07.26 [ 11023 ] 더하기 3 - 입출력 (0) 2021.07.26