백준 - 단어 공부(1157)

marafo·2020년 12월 18일
0

String

문제

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

입력

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

출력

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


100%까지 되다가 마지막에 런타임 에러 발생.

string = input().lower()
dic = {}

for i in range(len(string)):
    if string[i] in dic:
        dic[string[i]] += 1
    elif string[i] not in dic:
        dic[string[i]] = 1
        
dic = list(dic.items())
dic.sort(key = lambda x: x[1], reverse = True)


if dic[0][1] == dic[1][1]:
    print('?')
else:
    print(dic[0][0].upper())

dictionary말고 배열로 알파벳 빈도 체크한 풀이

word = input().lower()
wordList = list(set(word))
wordCount = []

for i in wordList: # 각 알파벳 유닛의 빈도를 wordCount에 넣는다.
    count = word.count(i)
    wordCount.append(count)
    
maxValue = max(wordCount) # 최다 빈도

if wordCount.count(maxValue) >= 2: # 최다 빈도(maxValue) 알파벳이 2번 이상 나오는지 체크
    print('?')
else:
    answer = wordCount.index(maxValue) # 최다 빈도 알파벳 추출
    print(wordList[answer].upper())

확실히 문자열 문제는 set이나 배열을 활용하는 센스가 중요하다.

참고)
https://ooyoung.tistory.com/70

profile
프론트 개발자 준비

0개의 댓글