반응형
문제
https://www.acmicpc.net/problem/1157
1157번: 단어 공부
알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.
www.acmicpc.net
풀이
- 대소문자 구분이 없기 때문에 입력받은 단어를 대문자로 바꾸는 작업이 필요함
- 알파벳이 key, 나온 빈도수를 value로 갖는 Dictionary를 초기화 해줘야 함
- 입력받은 단어를 하나씩 돌면서 Dictionary에 key가 있다면 +1, 없다면 1
이렇게 접근하여서 풀었는데 새롭게 알게된 사실이 있어요.
Dictionary를 초기화할 때, key를 기준으로 중복된 값을 알아서 더해주는 방식이 있어요
https://developer.apple.com/documentation/swift/dictionary/init(_:uniquingkeyswith:)
Apple Developer Documentation
developer.apple.com
즉, tuple을 Dictionary로 만들어 줄 수 있습니다.
이번 문제에도 활용할 수 있겠군요.
먼저 입력받은 단어를 (Character: Int)
형태의 튜플로 변환한 뒤, Dictionary로 변환하면 될 것입니다.
Int 자료형에는 1이 들어가면 되겠네요! 어차피 전부 더해주니깐요!
소스코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let dict = Dictionary(readLine()!.uppercased().map { ($0, 1) }, uniquingKeysWith: +) | |
let maxValueDict = dict.filter { $0.value == dict.values.max()! } | |
maxValueDict.count > 1 ? print("?") : print(maxValueDict.keys.first!) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let word = readLine()!.uppercased() | |
var dict: [Character: Int] = [:] | |
for w in word { | |
if let value = dict[w] { | |
dict[w] = value + 1 | |
} else { | |
dict[w] = 1 | |
} | |
} | |
dict = dict.filter { $0.value == dict.values.max()! } | |
dict.count > 1 ? print("?") : print(dict.keys.first!) |
후기
- uniquingKeysWith에 대해 처음 알게되었는데 유용하게 쓰일 것 같다.
- Dictionary에 대한 이해도만 있다면 쉽게 풀 수 있는 문제인 것 같다.
반응형
'PS > 백준' 카테고리의 다른 글
[BOJ] 백준 2908 상수 (Swift) (0) | 2023.01.02 |
---|---|
[BOJ] 백준 1152 단어의 개수 (Swift) (0) | 2023.01.02 |
[BOJ] 백준 2675 문자열 반복 (Swift) (0) | 2022.12.31 |
[BOJ] 백준 10809 알파벳 찾기 (Swift) (1) | 2022.12.30 |
[BOJ] 백준 11720 숫자의 합 (Swift) (0) | 2022.12.30 |