Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions design-add-and-search-words-data-structure/sonjh1217.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class WordDictionary {
class TrieNode {
var children: [Character: TrieNode] = [:]
var isEndOfWord = false
}

private var root: TrieNode

init() {
root = TrieNode()
}

// O(n) time / O(n) space
func addWord(_ word: String) {
var node = root

for character in word {
if node.children[character] == nil {
node.children[character] = TrieNode()
}

node = node.children[character]!
}

node.isEndOfWord = true
}

// O(m) ~ O(26^m) time / O(1) space
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

공간복잡도가 왜 O(1)이라고 생각하셨는지 여쭤봐도 될까요?? word의 길이만큼 공간이 필요하지 않나요..? 제가 잘 몰라서 여쭤봅니다..!!! 코드가 엄청 깔끔하고 좋네요 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e90ae4f 와 감사합니다! Array(word)며 재귀 스택 쌓이는거며 다 O(m)인데.. 왜 저렇게 생각했는지 모르겠네요ㅠ 아직 재귀에 대해서 잘 파악을 못해서 그랬던 것 같아요. 감사합니답!

func search(_ word: String) -> Bool {
return dfs(word: Array(word), index: 0, node: root)
}

private func dfs(word: [Character], index: Int, node: TrieNode) -> Bool {
if index == word.count {
return node.isEndOfWord
}

let character = word[index]

if character == "." {
for child in node.children.values {
if dfs(word: word, index: index + 1, node: child) {
return true
}
}
return false
} else {
guard let child = node.children[character] else {
return false
}
return dfs(word: word, index: index + 1, node: child)
}
}
}