본문 바로가기
알고리즘/BOJ(C++)

[BOJ 알고리즘] 1157 "단어 공부"

by frog 2021. 5. 12.

[BOJ 알고리즘] 1157 "단어 공부"


문제

  • 알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

● 소스코드

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

int main() {
	char str[1000001] = {};
	scanf("%[^\n]s",str);
	
	int count[27] = {};
	
	int answer = 0;
	int len = strlen(str);
	
	for(int i=0; i<len; i++)
	{
		if('A' <= str[i] && str[i] <= 'Z')
		{
			count[str[i] - 'A']++;
			answer = max(answer,count[str[i] - 'A']);
		}
		else if('a' <= str[i] && str[i] <= 'z')
		{
			count[str[i] - 'a']++;
			answer = max(answer,count[str[i] - 'a']);
		}
	}
	
	int index = -1;
	for(int i=0; i<27; i++)
	{
		if(answer == count[i])
		{
			if(index != -1)
			{
				printf("?\n");
				return 0;
			}
			else
			{
				index = i;
			}
		}
	}
	
	printf("%c\n",'A'+index);
	
	return 0;
}

 

풀이

    - 특별한 알고리즘은 없다.

    - 단어에서 문자의 갯수를 센다.

    - 가장 많이 사용된 문자를 대문자로 출력한다.

 

* www.acmicpc.net/problem/1157 

 

1157번: 단어 공부

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

www.acmicpc.net

댓글