백준문제풀이 6단계 심화 1(5) 1157번 단어 공부 (C#)

2024. 5. 31. 20:00백준 문제풀이/6단계 심화 1

 

대소문자로 이루어진 단어를 받고,

대소문자 상관없이 이 단어에 가장 많이 쓰인 알파벳을 출력하는 문제

쓰인 횟수가 같으면 ?를 출력한다.

 

using System;
using System.Collections.Generic;
using System.Linq;

class BackJoon
{
    static void Main(string[] args)
    {
        Dictionary<char, int> dic = new Dictionary<char, int>();
        string str = Console.ReadLine().ToUpper();
        int count = 0;
        foreach (var item in str)
        {
            if (dic.ContainsKey(item))
                dic[item]++;
            else
                dic[item] = 0;
        }
        var maxValueKey = dic.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;
        foreach (var item in dic)
        {
            if (item.Value == dic[maxValueKey])
                count++;
            if (count >= 2)
                break;
        }

        if (count == 1)
            Console.WriteLine(maxValueKey);
        else
            Console.WriteLine("?");
    }
}

 

Dictionary를 이용해 풀었다.

일단 문자열을 대문자로 바꿔준다

그다음 for문을 하나 돌려서 키값과 벨류값을 넣어주자.

이미 포함된 키값이면 ++를 해주고

없다면 0을 넣어준다.

 

다음으로 제일큰 벨류값을 찾아주고(벨류값의 키)

Dirctionary에서 그 벨류값이 몇개가 있는지 체크해준다.

maxVaul가 하나라면 그것을 출력

하나가 아니라면 ?를 출력.