문제 

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

 

입력

첫째 줄에 알파벳 대소문자로 이루어진 단어가 주어진다. 주어지는 단어의 길이는 1,000,000을 넘지 않는다.

 

출력 

첫째 줄에 이 단어에서 가장 많이 사용된 알파벳을 대문자로 출력한다. 단, 가장 많이 사용된 알파벳이 여러 개 존재하는 경우에는 ?를 출력한다.

 

예제1

입력:

Mississipi

출력

?

 

예제2

입력:

zZa

출력

Z

 

예제3

입력:

z

출력

Z

 

예제4

입력:

baaa

출력

A

 

 

코드

using System; 
using System.Collections.Generic;

class Program 
{ 
    static void Main(string[] args) 
    { 
        string word = Console.ReadLine().ToUpper();
        int maxCount = 0; 
        List<string> searched = new List<string>();
        List<int> count = new List<int>();
        
        for(int i=0; i<word.Length; i++) 
        { 
            if(!findElement(searched, word[i].ToString()))
            {
                int index = i;
                int total = 1;
                while(word.IndexOf(word[i], index+1)!=-1)
                {
                    index = word.IndexOf(word[i], index+1);
                    total++;
                }
                if(total > maxCount) maxCount = total;
                searched.Add(word[i].ToString());
                count.Add(total);
            }
        } 
        string[] searchedArr = searched.ToArray();
        int[] countArr = count.ToArray();
        int first = Array.IndexOf(countArr, maxCount);
        int second = Array.IndexOf(countArr, maxCount, first+1);
        
        if(second == -1) Console.Write(searchedArr[first]);
        else Console.Write("?");
    } 
    
    static bool findElement(List<string> list, string element) 
    {
        foreach(string word in list)
        {
            if(word == element) return true; 
        }
        return false; 
    }
}



설명:

먼저 입력받은 단어를 대문자로 변환한다. 

그런 다음 단어에 있는 알파벳 하나하나 돌아가면서 해당 알파벳이 단어에 포함되어 있는 수를 세고, 그 수를 count List에 저장한다. 

카운팅 완료된 알파벳은 searched List에 넣어 다음 알파벳을 확인할 때 searced List에 해당 알파벳이 있는지 체크하고 없으면 카운팅 작업을 시작한다. 

그리고 카운팅한 알파벳의 수가 가장 큰 경우에만 maxCount에 저장한다. 

루프 작업이 끝나면 List를 배열로 변환하고 countArr에 maxCount가 위치한 index를 구해서, searchedArr에서 해당 index에 위치한 단어를 구한다.

단, maxCount가 2군데 이상 있는 경우에는 "?"를 반환해야 하기 때문에 first에는 첫 번째 maxCount index를 저장하고 second에는 두 번 maxCount index를 저장한다. 

second가 -1이 아닌 경우, 즉 maxCount가 2군데 이상인 경우에만 "?"를 반환했다. 

 

 

+ Recent posts