壮志,敢教日月换新天。为有牺牲多

[Swift]字典树-Trie

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

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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  */
复制代码

 

posted @   为敢技术  阅读(291)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2018-11-24 [Xcode 实际操作]四、常用控件-(1)UIButton控件的使用
点击右上角即可分享
微信分享提示