[Algorithm] 백준 1371번 (파이썬) : 가장 많은 글자

Hyuk·2023년 2월 17일
0

https://www.acmicpc.net/problem/1371

풀이과정

아스키 코드로 변환하는 ord()chr()를 이용해주면 풀수 있는 문제이다.

여러 문장을 입력받기 위해 sys.stdin.read()를 사용해줬어야 했다.

코드

import sys
s = sys.stdin.read()
ch = [0] * 200
max = -2147000000

for i in s:
    if s.islower():
        ch[ord(i)] += 1

for i in range(len(ch)):
    if ch[i] > max:
        max = ch[i]
        
for i in range(len(ch)):
    if ch[i] == max:
        print(chr(i), end='')

다음과 같이 간략하게 코드를 짤수도 있다.

import sys
inStr, word = sys.stdin.read(), [0 for i in range(26)]
for s in inStr:
    if s.islower(): #소문자인지 체크
        word[ord(s)-97] += 1    # 알파벳을 아스키코드로 변환
for i in range(26):
    if word[i] == max(word):
        print(chr(i+97), end='')    #아스키코드에 해당되는 문자로 변환

대문자 A~Z까지의 아스키코드는 65번부터 90번, 소문자 a~z까지의 아스키코드는 97~122번까지이다.

참고(아스키 코드)

https://ddolcat.tistory.com/684

profile
프론트엔드 개발자

0개의 댓글

Powered by GraphCDN, the GraphQL CDN