[LeetCode] Implement Trie (Prefix Tree)

本文深入探讨了Trie数据结构的概念及其在代码实现中的应用,包括插入、搜索和前缀查找功能。通过实例代码,展示了如何高效地使用Trie解决字符串匹配问题。

You need to understand what a Trie is before writing the code :-) This link has a nice solution, whose code is rewritten below.

 1 class TrieNode {
 2 public:
 3     bool isWord;
 4     TrieNode* children[26];
 5     // Initialize your data structure here.
 6     TrieNode() : isWord(false) {
 7         memset(children, NULL, sizeof(TrieNode*) * 26);
 8     }
 9 };
10 
11 class Trie {
12 public:
13     Trie() {
14         root = new TrieNode();
15     }
16 
17     // Inserts a word into the trie.
18     void insert(string word) {
19         TrieNode* run = root;
20         for (char c : word) {
21             if (!(run -> children[c - 'a']))
22                 run -> children[c - 'a'] = new TrieNode();
23             run = run -> children[c - 'a'];
24         }
25         run -> isWord = true;
26     }
27 
28     // Returns if the word is in the trie.
29     bool search(string word) {
30         TrieNode* p = query(word);
31         return p && p -> isWord;
32     }
33 
34     // Returns if there is any word in the trie
35     // that starts with the given prefix.
36     bool startsWith(string prefix) {
37         return query(prefix);
38     }
39 
40 private:
41     TrieNode* root;
42     TrieNode* query(string& s) {
43         TrieNode* run = root;
44         for (char c : s) {
45             if (!(run -> children[c - 'a'])) return NULL;
46             run = run -> children[c - 'a'];
47         }
48         return run;
49     }
50 };
51 
52 // Your Trie object will be instantiated and called as such:
53 // Trie trie;
54 // trie.insert("somestring");
55 // trie.search("key");

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4737807.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值