Algorithm

λ°±μ€€ - 단어곡뢀(Swift)

CheonD 2022. 11. 8. 12:32

λ°±μ€€ - λ‹¨μ–΄κ³΅λΆ€(Swift)

 

 

 λ¬Έμ œ μ„€λͺ…

 

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

 

1157번: 단어 곡뢀

μ•ŒνŒŒλ²³ λŒ€μ†Œλ¬Έμžλ‘œ 된 단어가 주어지면, 이 λ‹¨μ–΄μ—μ„œ κ°€μž₯ 많이 μ‚¬μš©λœ μ•ŒνŒŒλ²³μ΄ 무엇인지 μ•Œμ•„λ‚΄λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€. 단, λŒ€λ¬Έμžμ™€ μ†Œλ¬Έμžλ₯Ό κ΅¬λΆ„ν•˜μ§€ μ•ŠλŠ”λ‹€.

www.acmicpc.net

 

 λ‚˜μ˜ 풀이

 

λ”•μ…”λ„ˆλ¦¬λ‘œ 갯수λ₯Ό μΉ΄μš΄νŠΈν•˜λ©΄ λ˜λŠ” μ‰¬μš΄ κ΅¬ν˜„λ¬Έμ œλ‹€.

 

λ”•μ…”λ„ˆλ¦¬λ₯Ό ν•„ν„°λ§ν•˜λ©΄ νŠœν”Œ 배열이 λ‚˜μ˜¬ 쀄 μ•Œμ•˜λŠ”λ° λ”•μ…”λ„ˆλ¦¬κ°€ λ‚˜μ™”μ—ˆλ‹€. (λ”•μ…”λ„ˆλ¦¬λ₯Ό mapν•˜λ©΄ 배열이 λ‚˜μ™€μ„œ κ·Έλ ‡κ²Œ μƒκ°ν–ˆλ‹€)

 

import Foundation

var dic: [Character: Int] = [:]

let str = readLine()!.uppercased()
str.forEach{ x in 
    if dic[x] == nil { dic[x] = 1}
    else { dic[x]! += 1}
}
let maxVal = dic.values.max()
let arr = dic.filter{$0.value == maxVal}
if arr.count > 1 {
    print("?")
} else {
    print(String(arr.keys))
}