Trie

一个人想着一个人 提交于 2020-07-29 09:45:43

参考

https://en.wikipedia.org/wiki/Trie

a trie, also called digital tree or prefix tree, is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings

也叫前缀树, 特定情况下替代set 和map。这时候key是字符串。


image

LeetCode:208. Implement Trie (Prefix Tree)
LeetCode:211. Add and Search Word - Data structure design
LeetCode:212. Word Search II


下面我们就一步步来实现Trie,并做题

一、初步实现Trie树结构


208. Implement Trie (Prefix Tree)

https://leetcode.com/problems/implement-trie-prefix-tree/description/


#include<cstdio>

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;


/**
* 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);
*/

const int letter_size=26;//字符集大小
struct TrieNode
{
TrieNode* children[letter_size]={0};
bool isWord = false;
TrieNode(){
}
~TrieNode(){
for(int i=0; i<letter_size; i++) if(children[i]) delete children[i];
}
};

struct Trie {
TrieNode* root;

/** Initialize your data structure here. */
Trie() {
root=new TrieNode();
}

~Trie(){
delete root;
}

int idx(char c)
{
return c - 'a';
}

/** Inserts a word into the trie. */
void insert(string word) {
TrieNode*p = root;
int len = word.length();
for(int i=0; i < len; i++){
int c = idx(word[i]);
if(!p->children[c])
p->children[c] = new TrieNode();
p = p->children[c];
}
p->isWord = true;
}

/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p=root;
int len = word.length();
for(int i=0; i < len; i++){
p = p->children[idx(word[i])];
if(!p)
return false;
}
return p->isWord;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string word) {
TrieNode *p=root;
int len = word.length();
for(int i=0; i < len; i++){
p = p->children[idx(word[i])];
if(!p)
return false;
}
return true;
}
};

int main()
{
Trie trie;

trie.insert("apple");
cout<< trie.search("apple") << endl;   // returns true
cout<< trie.search("app") << endl;     // returns false
cout<< trie.startsWith("app") << endl; // returns true
trie.insert("app");
cout<< trie.search("app") << endl;;     // returns true

return 0;
}


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!