题目:208. 实现 Trie (前缀树)
思路:经典的字典树题型,(Tire模板题)acwing 835. Trie字符串统计
C++版本:
class Trie {
public:
static const int N=1e6+5;
int p[N][30];
int ans[N];
int idx=0;
Trie() {
memset(p,0,sizeof p);
memset(ans,0,sizeof ans);
}
void insert(string word) {
int t=0;
for(auto x:word){
if(p[t][x-'a']==0){
p[t][x-'a']=++idx;
}
t=p[t][x-'a'];
}
ans[t]++;
}
bool search(string word) {
bool flag=1;
int t=0;
for(auto x:word){
if(p[t][x-'a']==0){
flag=0;
break;
}
t=p[t][x-'a'];
}
return flag&&ans[t];
}
bool startsWith(string prefix) {
bool flag=1;
int t=0;
for(auto x:prefix){
if(p[t][x-'a']==0){
flag=0;
break;
}
t=p[t][x-'a'];
}
return flag;
}
};
/**
* 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);
*/
JAVA版本:
class Trie {
private static final int N=100005;
int[][] p;
int[] ans;
int idx;
public Trie() {
p=new int[N][30];
ans=new int[N];
idx=0;
}
public void insert(String word) {
int t=0;
for(int i=0;i<word.length();i++){
char x=word.charAt(i);
if(p[t][x-'a']==0){
p[t][x-'a']=++idx;
}
t=p[t][x-'a'];
}
ans[t]++;
}
public boolean search(String word) {
boolean flag=true;
int t=0;
for(int i=0;i<word.length();i++){
char x=word.charAt(i);
if(p[t][x-'a']==0){
flag=false;
break;
}
t=p[t][x-'a'];
}
return flag&&ans[t]!=0;
}
public boolean startsWith(String prefix) {
boolean flag=true;
int t=0;
for(int i=0;i<prefix.length();i++){
char x=prefix.charAt(i);
if(p[t][x-'a']==0){
flag=false;
break;
}
t=p[t][x-'a'];
}
return flag;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/