[leetcode] 208. Implement Trie (Prefix Tree)

网友投稿 251 2022-08-26

[leetcode] 208. Implement Trie (Prefix Tree)

Description

Implement a trie with insert, search, and startsWith methods.

Example:

Trie trie = new Trie();trie.insert("apple");trie.search("apple"); // returns truetrie.search("app"); // returns falsetrie.startsWith("app"); // returns truetrie.insert("app"); trie.search("app"); // returns true

Note:

You may assume that all inputs are consist of lowercase letters a-z.All inputs are guaranteed to be non-empty strings.

分析

题目的意思是:实现一个字典树。

Trie树,又叫字典树、前缀树(Prefix Tree)、单词查找树或键树,是一种多叉树结构。

上图是一棵Trie树,表示了关键字集合{“a”, “to”, “tea”, “ted”, “ten”, “i”, “in”, “inn”} 。从上图可以归纳出Trie树的基本性质:

①根节点不包含字符,除根节点外的每一个子节点都包含一个字符。

②从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。

③每个节点的所有子节点包含的字符互不相同。

④从第一字符开始有连续重复的字符只占用一个节点,比如上面的to,和ten,中重复的单词t只占用了一个节点。

要实现insert,search,startswith函数。unordered_map表类存储字符和结点的映射,insert方法就是在unordered_map上查找创建的过程。search是map上的遍历过程。startwith也是一样的查找。

代码

class TrieNode{ public: unordered_map children; bool isLeaf; TrieNode(){isLeaf = false;};};class Trie {private: TrieNode* root;public: /** Initialize your data structure here. */ Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ void insert(string word) { TrieNode *cur = root; for(int i=0;ichildren.find(word[i])==cur->children.end()){ cur->children[word[i]] = new TrieNode(); } cur=cur->children[word[i]]; } cur->isLeaf=true; } /** Returns if the word is in the trie. */ bool search(string word) { TrieNode *cur = root; for(int i=0;ichildren.find(word[i])==cur->children.end()){ return false; } cur=cur->children[word[i]]; } if(cur->isLeaf){ return true; } return false; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { TrieNode *cur = root; for(int i=0;ichildren.find(prefix[i])==cur->children.end()){ return false; } cur=cur->children[prefix[i]]; } 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); */

参考文献

​​leetcode 208 Implement Trie C++​​​​前缀树(Trie)原理及Java实现​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:冬奥会出圈的Lululemon是怎么成为营销鬼才的?
下一篇:[leetcode] 334. Increasing Triplet Subsequence
相关文章

 发表评论

暂时没有评论,来抢沙发吧~