208. Implement Trie (Prefix Tree)

本文介绍了一种Trie树的数据结构实现方式,并提供了插入、搜索和前缀匹配三种主要操作的具体实现。通过C++代码详细解释了如何进行节点创建、单词插入及查找等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement a trie with insertsearch, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.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的基本实现:

 1 struct TrieNode{
 2     TrieNode* children[26];
 3     bool isWord;
 4     TrieNode(){
 5         for(int i=0;i<26;i++){
 6             children[i]=NULL;
 7         }
 8     }
 9     ~TrieNode(){
10         for(int i=0;i<26;i++){
11             delete children[i];
12         }
13     }
14 };
15 class Trie {
16 private:
17     TrieNode* root;
18 public:
19     /** Initialize your data structure here. */
20     Trie() {
21         root = new TrieNode();
22     }
23     
24     /** Inserts a word into the trie. */
25     void insert(string word) {
26         TrieNode* curr = root;
27         for(auto c: word){
28             if(curr->children[c-'a']==NULL){
29                 curr->children[c-'a'] = new TrieNode();
30             }
31             curr = curr->children[c-'a'];
32         }
33         curr->isWord = true;
34     }
35     
36     /** Returns if the word is in the trie. */
37     bool search(string word) {
38         TrieNode* curr = root;
39         for(auto c: word){
40             if(curr->children[c-'a']==NULL){
41                 return false;  
42             }
43             curr = curr->children[c-'a'];
44         }
45         
46         return curr->isWord;
47     }
48     
49     /** Returns if there is any word in the trie that starts with the given prefix. */
50     bool startsWith(string prefix) {
51         TrieNode* curr = root;
52         for(auto c: prefix){
53             if(curr->children[c-'a']==NULL){
54                 return false;
55             }
56             curr=curr->children[c-'a'];
57         }
58         
59         return true;
60     }
61 };
62 
63 /**
64  * Your Trie object will be instantiated and called as such:
65  * Trie obj = new Trie();
66  * obj.insert(word);
67  * bool param_2 = obj.search(word);
68  * bool param_3 = obj.startsWith(prefix);
69  */

 

转载于:https://www.cnblogs.com/ruisha/p/9311035.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值