一、题目
Trie(发音类似 "try")或者说 前缀树 是一种树形数据布局,用于高效地存储和检索字符串数据集中的键。这一数据布局有相当多的应用景象,例如自动补全和拼写查抄。
请你实现 Trie 类:
- Trie() 初始化前缀树对象。
- void insert(String word) 向前缀树中插入字符串 word 。
- boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
- boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
示例:
- <strong>输入</strong>
- ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
- [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
- <strong>输出</strong>
- [null, null, true, false, true, null, true]
- <strong>解释</strong>
- Trie trie = new Trie();
- trie.insert("apple");
- trie.search("apple"); // 返回 True
- trie.search("app"); // 返回 False
- trie.startsWith("app"); // 返回 True
- trie.insert("app");
- trie.search("app"); // 返回 True
复制代码
提示:
- 1 <= word.length, prefix.length <= 2000
- word 和 prefix 仅由小写英文字母构成
- insert、search 和 startsWith 调用次数 总计 不超过 3 * 10^4 次
二、解题思路
Trie树,又称字典树,其工作原理类似于查字典的过程。举个例子,如果我们要查找单词“wo”,首先需要定位到字母“w”,然后再找到字母“o”。从布局上看,Trie树可以理解为一棵多叉树,每个节点最多可以拥有多个子节点。在本题中,由于单词和前缀仅由小写英文字母构成,而小写字母共有26个,因此Trie树可以被视为一棵26叉树。下图展示了这种布局的具体情势。
Trie树的布局从一个空的根节点开始,根节点本身并不存储任何具体的值。从根节点出发,可以延伸出最多26个子节点,每个子节点又可以进一步扩展出最多26个子节点,以此类推。以字符串为例,假设我们有以下几个字符串:
- "ac"
- "bcd"
- "ace"
- "ef"
它们在Trie树中的存储方式如下:
1. 从根节点出发,字符串“ac”会沿着路径 `a -> c` 存储。
2. 字符串“bcd”会沿着路径 `b -> c -> d` 存储。
3. 字符串“ace”会沿着路径 `a -> c -> e` 存储。
4. 字符串“ef”会沿着路径 `e -> f` 存储。
通过这种方式,Trie树能够高效地存储和检索字符串,同时共享相同的前缀以减少空间占用。
然而,这里存在一个问题:虽然我们没有明确存储字符串“bc”,但上面的Trie树中却包罗了“bc”这一路径。此外,路径中还包罗了“a”、“b”、“e”等字符。实际上,这些字符并不是一个完整的字符串,而是我们存储的某些字符串的前缀。那么,如何区分一个路径是否代表一个完整的字符串呢?为相识决这个问题,我们需要对字符串的最后一个字符进行特别标志,表现这是一个完整字符串的竣事。具体实现方式如下图所示。
如上图所示,字符串“bc”并不是一个完整的字符串,由于它的最后一个字符“c”没有被标志为竣事节点。至于如何标志一个字符串的竣事,可以根据具体需求来计划。在这里,我们使用一个布尔类型的变量来进行标志,表现某个节点是否为某个字符串的末端。
需要留意的是,这里的节点类并没有直接存储单个字符的值。我们通过判断某个子节点是否为空,来推断对应的字符是否存在。例如,如果我们想查找字符“a”,由于“a”对应的是26个子节点中的第一个节点,我们只需要查抄第一个子节点是否为空即可。如果该子节点为空,分析字符“a”不存在;反之,则分析字符“a”存在。
三、代码实现
- #include <iostream>
- #include <string>
- using namespace std;
- // Trie 节点类
- class TrieNode {
- public:
- TrieNode* children[26]; // 26 个子节点,对应 26 个小写字母
- bool isWord; // 标记是否为完整单词的结尾
- TrieNode() {
- for (int i = 0; i < 26; i++) {
- children[i] = nullptr;
- }
- isWord = false;
- }
- };
- // Trie 类
- class Trie {
- private:
- TrieNode* root; // 根节点
- public:
- Trie() {
- root = new TrieNode();
- }
- // 插入字符串
- void insert(string word) {
- TrieNode* parentNode = root;
- for (char ch : word) {
- int index = ch - 'a'; // 计算字符对应的索引
- if (parentNode->children[index] == nullptr) {
- parentNode->children[index] = new TrieNode(); // 如果子节点不存在,则创建
- }
- parentNode = parentNode->children[index]; // 更新父节点
- }
- parentNode->isWord = true; // 标记为完整单词
- }
- // 查找是否是一个完整的字符串
- bool search(string word) {
- TrieNode* node = find(word);
- return node != nullptr && node->isWord;
- }
- // 判断是否有以 prefix 为前缀的字符串
- bool startsWith(string prefix) {
- return find(prefix) != nullptr;
- }
- private:
- // 查找字符串对应的节点
- TrieNode* find(string str) {
- TrieNode* parentNode = root;
- for (char ch : str) {
- int index = ch - 'a';
- if (parentNode->children[index] == nullptr) {
- return nullptr; // 如果某个字符不存在,返回 nullptr
- }
- parentNode = parentNode->children[index]; // 更新父节点
- }
- return parentNode; // 返回最后一个字符对应的节点
- }
- };
- // 测试代码
- int main() {
- Trie trie;
- trie.insert("apple");
- cout << "Search 'apple': " << (trie.search("apple") ? "Found" : "Not Found") << endl; // 输出: Found
- cout << "Search 'app': " << (trie.search("app") ? "Found" : "Not Found") << endl; // 输出: Not Found
- cout << "Starts with 'app': " << (trie.startsWith("app") ? "Yes" : "No") << endl; // 输出: Yes
- trie.insert("app");
- cout << "Search 'app': " << (trie.search("app") ? "Found" : "Not Found") << endl; // 输出: Found
- return 0;
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |