今天刷到一个题,要我们设计一个数据结构能够快速匹配字符串的数据结构。也就是大名鼎鼎的字典树。也可以叫做前缀匹配树。像路由器对分组的ip与路由表项匹配的时候用的数据结构就是这个。
还是蛮重要的,故提笔记之
下面请看题
思路:像这个题,我们需要设计的字典树的度为26(因为有26个字母)。树上每个节点到根的路径是唯一的,故都可以代表一个字符串。因为有的时候我们插入的字符串可能是已经插入的字符串的子串,所以我们需要在每个节点里面设置一个布尔字段is_end.表示是否有以当前节点结尾的字符串。这样我们每次插入字符串时,从字符串第一个字符一个一个的插入,在插入的过程中可以创建新的节点,因为存在’.'可以匹配任意字符,所以我们可以设置递归插入会更省事点,要不然我们就得在某一次迭代里面插入26次了。不好组织代码。
废话说了那麽多,还是先贴上代码把
class WordDictionary {
private:
struct node{
vector<node *> arr;
bool is_end;
node(){
arr.resize(26,nullptr);
is_end = false;
}
};
node *head;
protected:
void insert(node *cur, int s, string &word){
if(s==word.size()){
cur->is_end=true;
return ;
}
if(word[s]=='.'){
for(int i=0;i<26;i++){
if(cur->arr[i]==nullptr){
cur->arr[i]=new node;
}
insert(cur->arr[i],s+1,word);
}
}else{
if(cur->arr[word[s]-'a']==nullptr){
cur->arr[word[s]-'a'] = new node;
}
insert(cur->arr[word[s]-'a'], s+1, word);
}
}
bool comp(node *cur, string &word, int s){
if(cur==nullptr){
return false;
}
if(s==word.size()){
return cur->is_end;
}
char c= word[s];
if(c=='.'){
bool flag = false;
for(int i=0;i<26;i++){
flag=flag||comp(cur->arr[i],word, s+1);
}
return flag;
}else{
return comp(cur->arr[c-'a'], word, s+1);
}
}
public:
WordDictionary() {
head = new node;
}
void addWord(string word) {
insert(head, 0, word);
}
bool search(string word) {
return comp(head, word, 0);
}
};