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
๋ฐ์ํ
๋๊ธ