|
| 1 | +class WordDictionary { |
| 2 | + let root: TrieNode |
| 3 | + |
| 4 | + init() { |
| 5 | + root = TrieNode() |
| 6 | + } |
| 7 | + |
| 8 | + func addWord(_ word: String) { |
| 9 | + let spread = Array(word) |
| 10 | + var node = root |
| 11 | + |
| 12 | + for letter in spread { |
| 13 | + if let child = node.children[letter] { |
| 14 | + node = child |
| 15 | + } else { |
| 16 | + let newNode = TrieNode() |
| 17 | + node.children[letter] = newNode |
| 18 | + node = newNode |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + node.isTerminating = true |
| 23 | + } |
| 24 | + |
| 25 | + func search(_ word: String) -> Bool { |
| 26 | + return traverse(root, Array(word), 0) |
| 27 | + } |
| 28 | + |
| 29 | + private func traverse(_ node: TrieNode, _ quote: [Character], _ starting: Int) -> Bool { |
| 30 | + if starting == quote.count { |
| 31 | + return node.isTerminating |
| 32 | + } |
| 33 | + |
| 34 | + let letter = quote[starting] |
| 35 | + |
| 36 | + if letter == "." { |
| 37 | + var result = false |
| 38 | + |
| 39 | + for key in node.children.keys { |
| 40 | + if let child = node.children[key] { |
| 41 | + result = result || traverse(child, quote, starting + 1) |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return result |
| 46 | + } else { |
| 47 | + guard let child = node.children[letter] else { |
| 48 | + return false |
| 49 | + } |
| 50 | + |
| 51 | + return traverse(child, quote, starting + 1) |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +class TrieNode { |
| 57 | + var isTerminating: Bool |
| 58 | + var children: [Character: TrieNode] |
| 59 | + |
| 60 | + init(isTerminating: Bool = false, children: [Character: TrieNode] = [:]) { |
| 61 | + self.isTerminating = isTerminating |
| 62 | + self.children = children |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Your WordDictionary object will be instantiated and called as such: |
| 68 | + * let obj = WordDictionary() |
| 69 | + * obj.addWord(word) |
| 70 | + * let ret_2: Bool = obj.search(word) |
| 71 | + */ |
0 commit comments