leetcode 链接:208. 实现 Trie (前缀树)
题目
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
Trie()初始化前缀树对象。void insert(String word)向前缀树中插入字符串word。boolean search(String word)如果字符串 word 在前缀树中,返回true(即,在检索之前已经插入);否则,返回false。boolean startsWith(String prefix)如果之前已经插入的字符串word的前缀之一为prefix,返回true;否则,返回false。
word 和 prefix 仅由小写英文字母组成
示例:
输入["Trie", "insert", "search", "search", "startsWith", "insert", "search"][[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]输出[null, null, true, false, true, null, true]解释Trie trie = new Trie();trie.insert("apple");trie.search("apple"); // 返回 Truetrie.search("app"); // 返回 Falsetrie.startsWith("app"); // 返回 Truetrie.insert("app");trie.search("app"); // 返回 True
解答 & 代码
// Trie 树的节点类(不需要存储节点代表的字母,当前节点是父节点的第几个孩子,就是第几个字母)struct Node {vector<Node*> children; // 孩子节点的指针 数组bool isLeaf; // 当前节点是否是叶子节点(即当前是否代表一个字符串的结束)// 将 children 数组初始化为包含 26 个孩子节点的指针,且都初始化为 nullptr// 将当前节点初始化为非叶子节点Node() : children(26, nullptr), isLeaf(false) {}};class Trie {private:Node* root; // 根节点public:/** Initialize your data structure here. */Trie() {root = new Node();}/** Inserts a word into the trie. */void insert(string word) {Node* cur = root;int size = word.size();for(int i = 0; i < size; ++i){int idx = word[i] - 'a';if(cur->children[idx] == nullptr)cur->children[idx] = new Node();cur = cur->children[idx];}cur->isLeaf = true; // 将代表最后一个字符的节点设为叶子节点}/** Returns if the word is in the trie. */bool search(string word) {Node* cur = root;int size = word.size();for(int i = 0; i < size; ++i){int idx = word[i] - 'a';if(cur->children[idx] == nullptr)return false;cur = cur->children[idx];}return cur->isLeaf;}/** Returns if there is any word in the trie that starts with the given prefix. */bool startsWith(string prefix) {Node* cur = root;int size = prefix.size();for(int i = 0; i < size; ++i){int idx = prefix[i] - 'a';if(cur->children[idx] == nullptr)return false;cur = cur->children[idx];}return true;}};/*** Your Trie object will be instantiated and called as such:* Trie* obj = new Trie();* obj->insert(word);* bool param_2 = obj->search(word);* bool param_3 = obj->startsWith(prefix);*/
复杂度分析:设每次插入 or 查询的字符串长度为 S;所有插入字符串长度之和为 T
- 时间复杂度:初始化 O(1),其余操作 O(S)
- 空间复杂度:O(26T)
执行结果:
执行结果:通过
执行用时:44 ms, 在所有 C++ 提交中击败了 98.06% 的用户
内存消耗:47.1 MB, 在所有 C++ 提交中击败了 36.50% 的用户
