Skip to content

Instantly share code, notes, and snippets.

@rurumimic
Created September 14, 2018 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rurumimic/59cbe9deb9f7701b52654bba37b0b8a8 to your computer and use it in GitHub Desktop.
Save rurumimic/59cbe9deb9f7701b52654bba37b0b8a8 to your computer and use it in GitHub Desktop.
2017 카카오 3차 5번 내 풀이
import Foundation
class Node {
var parent: Node?
var childrens: [Character:Node] = [:]
var isWord: Bool = false
var count: Int = 0
init(parent: Node?) {
self.parent = parent
}
}
func find(_ node: Node, _ key: String) -> Bool {
var currentNode = node
for char in key {
if let value = currentNode.childrens[char] {
currentNode = value
} else {
return false
}
}
return currentNode.isWord
}
func insert(_ root: Node, _ word: String, _ value: Bool) {
var currentNode = root
var indexLastCharacter = -1
for (n, c) in word.enumerated() {
if let value = currentNode.childrens[c] {
currentNode = value
currentNode.count += 1
} else {
indexLastCharacter = n
break
}
}
if indexLastCharacter != -1 {
for c in Array(word)[indexLastCharacter...] {
currentNode.childrens[c] = Node(parent: currentNode)
currentNode = currentNode.childrens[c]!
currentNode.count += 1
}
}
currentNode.isWord = value
}
func childs(_ root: Node, _ key: String) -> Int {
var currentNode = root
var depth = 0
for char in key {
if currentNode.count == 1 {
return depth
}
currentNode = currentNode.childrens[char]!
depth += 1
}
return key.count
}
func solution(_ words:[String]) -> Int {
let root = Node(parent: nil)
for word in words {
insert(root, word, true)
}
// print(find(root, "go"))
// print(find(root, "gone"))
// print(find(root, "guild"))
// print(find(root, "cat"))
var sum = 0
for word in words {
sum += childs(root, word)
// print(sum)
}
return sum
}
print(solution(["go", "gone", "guild"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment