π Problem Solution/Programmers
[Swift] 2020 KAKAO BLIND RECRUITMENT κ°μ¬ κ²μ
Fomagran π»
2022. 1. 3. 19:34
728x90
λ°μν
Problem
Solution
ν΄λΉ λ¬Έμ λ Trie μλ£κ΅¬μ‘°λ₯Ό μ¬μ©ν΄μ νμ΄μΌ νλ λ¬Έμ μ λλ€.
(Trie κ΄λ ¨ν΄μλ λ°λ‘ μ 리ν΄μ μ¬λ¦¬λλ‘ νκ² μ΅λλ€!γ )
1. Trie μλ£ κ΅¬μ‘°λ₯Ό λ§λ€μ΄μ€λ€.
μ μμΌλ‘ λ§λ 건 μλκ³ κ°λ¨νκ² λ¨μ΄λ₯Ό Trie μλ£κ΅¬μ‘°μ λ§κ² μ½μ νλ insert λ©μλμ
κΈμμ μμμ΄ λͺ κ° μλμ§ μΈμ΄μ£Όλ getCount λ©μλλ₯Ό ꡬννμ΅λλ€.
class Node {
var value:String
var count:Int = 0
var children:[String:Node] = [:]
init(value:String) {
self.value = value
}
func append(_ value:String) {
self.children[value] = Node(value: value)
}
}
class Trie {
let root:Node = Node(value:"")
func insert(_ word:String) {
var current = root
let map = word.map{String($0)}
map.forEach {
current.count += 1
if !current.children.keys.contains($0) {
current.append($0)
}
current = current.children[$0]!
}
}
func getCount(_ word:String) -> Int {
var current = root
let map = word.map{String($0)}
for w in map {
if !current.children.keys.contains(w) {
return 0
}
current = current.children[w]!
}
return current.count == 0 ? 1 : current.count
}
}
2. μ¬λ°λ₯Έ Trieμ λ€μ§μ΄μ§ κΈμλ₯Ό λ΄μ Trieλ₯Ό λ§λ€μ΄μ€λ€.
κΈμλ‘ μμνλ λ¨μ΄λ μ¬λ°λ₯Έ trieλ‘, ?λ‘ μμνλ λ¨μ΄λ λ€μ§μ΄μ§ trieμΈ reverseλ‘ λ°λ‘ κ΄λ¦¬ν΄μ€λλ€.
struct Tries {
var trie:Trie,reverse:Trie
}
3. λ¨μ΄ κ°―μμ λ§κ² λΆλ₯ν΄μ€λ€.
func classifyByWordLength(_ words:[String]) -> [Int:Tries] {
var lengthDic:[Int:Tries] = [:]
for word in words {
if lengthDic[word.count] == nil {
let tries = Tries(trie: Trie(), reverse: Trie())
tries.trie.insert(word)
tries.reverse.insert(String(word.reversed()))
lengthDic[word.count] = tries
}else {
lengthDic[word.count]!.trie.insert(word)
lengthDic[word.count]!.reverse.insert(String(word.reversed()))
}
}
return lengthDic
}
4. 쿼리μ λ§κ² κ°―μλ₯Ό λ΄μμ€λ€.
μ£Όμν μ μ query μμ λ¨μ΄μ κΈΈμ΄κ° lengthDicμ μλ€λ©΄ 0μ λ°ννλ κ²μ λλ€.
func queriesResults(_ queries:[String],_ lengthDic:[Int:Tries]) -> [Int] {
var results:[Int] = []
for query in queries {
let count = query.count
if lengthDic[count] == nil {
results.append(0)
continue
}
var pre = query.map{String($0)}.filter{$0 != "?"}.joined()
pre = query.first == "?" ? String(pre.reversed()) : pre
let trie = query.first == "?" ? lengthDic[count]!.reverse : lengthDic[count]!.trie
let result = trie.getCount(pre)
results.append(result)
}
return results
}
5. resultsλ₯Ό λ°ννλ€.
func solution(_ words:[String], _ queries:[String]) -> [Int] {
let lengthDic:[Int:Tries] = classifyByWordLength(words)
return queriesResults(queries,lengthDic)
}
Source Code
728x90
λ°μν