[Swift]字典树-Trie

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(let_us_code)
➤博主域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11923061.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Trie树,字典树是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

例如我们往字典树中插入see、pain、paint三个单词,Trie字典树如下所示:

这里写图片描述

 参见:[Swift]LeetCode208. 实现 Trie (前缀树) | Implement Trie (Prefix Tree)

 1 class Node {
 2     var wordEnd = false
 3     var next : [Character : Node] = [:]
 4 }
 5 
 6 class Trie {
 7     let root = Node()
 8     /** Initialize your data structure here. */
 9     init() {
10         
11     }
12     
13     /** Inserts a word into the trie. */
14     func insert(_ word: String) {
15       var currentNode = root
16         for c in word {
17             if let nextNode = currentNode.next[c] {
18                 currentNode = nextNode
19             } else {
20                 let nextNode = Node()
21                 currentNode.next[c] = nextNode
22                 currentNode = nextNode
23             }
24         }
25         currentNode.wordEnd = true
26     }
27     
28     /** Returns if the word is in the trie. */
29     func search(_ word: String) -> Bool {
30       var currentNode = root
31       for c in word {
32           if let node = currentNode.next[c] {
33               currentNode = node
34           } else {
35               return false
36           }
37       }
38         return currentNode.wordEnd
39     }
40     
41     /** Returns if there is any word in the trie that starts with the given prefix. */
42     func startsWith(_ prefix: String) -> Bool {
43       var currentNode = root
44       for c in prefix {
45           if let node = currentNode.next[c] {
46               currentNode = node
47           } else {
48               return false
49           }
50       }
51         return true
52     }
53 }
54 
55 /**
56  * Your Trie object will be instantiated and called as such:
57  * let obj = Trie()
58  * obj.insert(word)
59  * let ret_2: Bool = obj.search(word)
60  * let ret_3: Bool = obj.startsWith(prefix)
61  */
原文地址:https://www.cnblogs.com/strengthen/p/11923061.html