目录
Trie 树(又叫前缀树或字典树)是一种用于快速查询某个字符串或字符前缀是否存在的数据结构。
其核心是使用「边」来代表有无字符,使用「点」来记录是否为「单词结尾」以及「其后续字符串的字符是什么」。
LeetCode208 实现Trie(前缀树)
/*
* @lc app=leetcode.cn id=208 lang=cpp
*
* [208] 实现 Trie (前缀树)
*/
// @lc code=start
#include<iostream>
#include<string>
using namespace std;
class Trie {
private:
Trie* son[26];
bool isWord;
public:
Trie() {
isWord=false;
for(int i=0;i<26;i++)son[i]=nullptr;
}
void insert(string word) {
Trie* root=this;//this 是一个指向当前对象的指针
for(char c:word){
int index=c-'a';
if(root->son[index]==nullptr){
root->son[index]=new Trie();
}
root=root->son[index];
}
root->isWord=true;
}
bool search(string word) {
Trie* root=this;
for(char c:word){
int index=c-'a';
if(root->son[index]==nullptr){return false;}
root=root->son[index];
}
return root->isWord;
}
bool startsWith(string prefix) {
Trie* root=this;
for(char c:prefix){
int index=c-'a';
if(root->son[index]==nullptr) return false;
root=root->son[index];
}
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);
*/
// @lc code=end
int main(){
Trie* trie=new Trie();//创建了一个Trie对象的指针,只能使用指针访问方式调用insert函数
trie->insert("apple");
bool f1=trie->search("apple");
if(f1==true){
cout<<"True"<<endl;
}
else{
cout<<"False"<<endl;
}
bool f2=trie->search("app");
if(f2==true) cout<<"True"<<endl;
else cout<<"False"<<endl;
trie->startsWith("app");
bool f3=trie->startsWith("app");
if(f3==true) cout<<"True"<<endl;
else cout<<"False"<<endl;
trie->insert("app");
bool f5=trie->search("app");
if(f5==true) cout<<"True"<<endl;
else cout<<"False"<<endl;
Trie trie2; //声明时会自动调用默认构造函数 Trie() 进行初始化操作
}
LeetCode1032 字符流(华为)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Trie{
public:
bool isWord;
Trie *son[26];
Trie(){
isWord=false;
for(int i=0;i<26;i++){
son[i]=nullptr;
}
}
void insert(string& word){//将word的倒序存储在字典树中
reverse(word.begin(),word.end());
Trie *node=this;
for(char& c:word){
int index=c-'a';
if(node->son[index]==nullptr){
node->son[index]=new Trie;
}
node=node->son[index];
}
node->isWord=true;
}
bool search(string& s){//搜索s的倒序的前缀是否存在于words当中
Trie *node=this;
for(int i=s.size()-1;i>=0;i--){
int index=s[i]-'a';
if(node->son[index]==nullptr) return false;
node=node->son[index];
if(node->isWord==true) return true;
}
return false;
}
};
class StreamChecker {
public:
Trie *t=new Trie;
string s="";
StreamChecker(vector<string>& words) {
for(int i=0;i<words.size();i++){
t->insert(words[i]);
}
}
bool query(char letter) {
s+=letter;
return t->search(s);
}
};