본문 바로가기

Language/C++

[C++][백준 1157][문자열] 단어 공부- 컴도리돌이

728x90

문제

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

  • 입력 값은 첫째 줄에 알파벳 대소문자로 이루어진 단어가 주어진다.

  • 출력 값으로는 가장 많이 사용된 알파벳이 대문자로 출력된다. (가장 많이 사용된 알파벳이 여러 개 존재할 경우 '?'출력


소스 코드

  • 해당 코드는 입력받은 문자열에서 알파벳이 나올 때마다 해당 위치의 arr의 값을 증가시켜줬다.
  • arr 값을 설정해주고 해당 arr에서 max값을 갖는 index를 저장한다.
  • 만약 max값을 갖는 index가 존재할 경우 flag를 증가시켜준다.
  • 출력할 때 중복 flag가 설정되어 있으면 '?'을 출력, 아닐 경우 해당 index의 알파벳을 출력.
  • 소문자, 대문자를 구분해주기 위해서 아스키코드 값으로 나누어 줬는데 코드가 매우 지저분하다.
#include<iostream>
#include<string>

using namespace std;

int main(void)
{
    string input;
    string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    cin >> input;
    int arr[26] = {0,};
    int max_index=0,max_index_count =0,if_max_index_two_flag =0;

    for(int i=0; i<input.length(); i++)
    {
        if((int)input[i] > 90)
        {
            arr[(int)input[i]-97]++;
        }
        else
        {
            arr[(int)input[i]-65]++;
        }
        
    }
    for(int i=0; i<26 ; i++)
    {
        if(arr[i] >= max_index_count)
        {
            if(arr[i] == max_index_count)
            {
                if_max_index_two_flag=1;
            }
            else
            {
                if_max_index_two_flag = 0;
                max_index = i;
                max_index_count = arr[i];
            }
        }
    }

    if(if_max_index_two_flag == 1)
    {
        cout << "?";
    }
    else
    {
        cout << alpha[max_index];
    }
    return 0;
}

 

다른 사람의 소스 코드

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    string c;
    cin >> c;
    int max = 0;
    int cnt = 0;
    int target;
    int a[26] = {0,};
    transform(c.begin(), c.end(), c.begin(), (int(*)(int))toupper);
    for(int i = 0; i < c.length(); i++)
    {
        a[c[i] - 'A']++;
    }

    for(int i = 0; i < 26; i++)
    {
        if(max < a[i])
        {
            max = a[i];
            cnt = 0;
            target = i;
        }
        if(max == a[i])
            cnt++;
    }
    if(cnt > 1)
        cout << "?";
    else
        cout << (char)(target+'A');
    return 0;
}

다른 거는 모르겠고, 이 분은 입력받은 문자열을 처음부터 다 대문자로 바꿔주고 시작하였다. 그래서 내 소스 코드처럼 지저분한 부분이 존재하지 않는다.

transform(c.begin(), c.end(), c.begin(), (int(*)(int))toupper); string 문자열을 대문자로 변환