实现一个 Trie (前缀树),包含
insert
,search
, 和startsWith
这三个操作。示例:
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说明:
- 你可以假设所有的输入都是由小写字母
a-z
构成的。- 保证所有输入均为非空字符串。
一道前缀树(字典树)的模板题,这里就不介绍字典树的实现原理了。
一些注释直接写在代码里。
struct node { bool istrie;//判断到此处节点时,组成的串是否是一个字符串,默认为false,只有到输入的最后一个节点时,变成true; node *nxt[26];//用来映射26个字母。 node():istrie(false) { for(int i=0;i<26;i++) nxt[i]=NULL; } }; class Trie { private: node *t_node; public: /** Initialize your data structure here. */ Trie() { t_node=new node(); } /** Inserts a word into the trie. */ void insert(string word) { if(word=="") //空串 return; node *temp=t_node; for(int i=0;i<word.size();i++) { if((temp->nxt)[word[i]-'a']==NULL) { node *t_nde=new node(); (temp->nxt)[word[i]-'a']=t_nde; temp=(temp->nxt)[word[i]-'a']; } else { temp=(temp->nxt)[word[i]-'a']; } } temp->istrie=true; } /** Returns if the word is in the trie. */ bool search(string word) { if(""==word||t_node==NULL) return false; node *temp=t_node; for(int i=0;i<word.size();i++) { if((temp->nxt)[word[i]-'a']==NULL) return false; else temp=(temp->nxt)[word[i]-'a']; } if(temp->istrie) return true; else return false; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { if(prefix==""||t_node==NULL) return false; node *temp=t_node; for(int i=0;i<prefix.size();i++) { if((temp->nxt)[prefix[i]-'a']==NULL) return false; else temp=(temp->nxt)[prefix[i]-'a']; } 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. 实现 Trie (前缀树)
最新推荐文章于 2025-04-14 11:38:03 发布