標籤:value bsp 匹配 null 指標 雜湊表 void 指標 blog int
字典樹是首碼匹配問題中常用的資料結構,查詢速度可以達到O(len),len為待查序列的長度,但是字典樹的空間消耗非常大,對於基於字母表的英文單詞,每個節點要儲存26個指標指向下一節點,很有可能有不少空的,很浪費。
考慮在節點中用雜湊表來儲存子節點指標,索引值為單個字母,這樣對於模式中沒有的字母就省掉了null 指標的空間,同樣可以達到O(1)的選擇分支速度。
1 //用map作雜湊表 2 class Node 3 { 4 public: 5 bool is_word = false; 6 map<char, Node *> children; 7 ~Node() 8 { 9 for (int i = 0; i < 26; ++i)10 {11 if (children.find(‘a‘ + i) != children.end()) delete children[‘a‘ + i];12 }13 }14 void insert(const string _Word)15 {16 Node *p = this;17 for (int i = 0; i < _Word.size(); ++i)18 {19 char curr = _Word[i];20 if (p->children.find(curr) == p->children.end())21 {22 p->children.insert(map<char, Node *>::value_type{ curr,new Node() });23 }24 p = p->children[curr];25 }26 p->is_word = true;27 }28 bool has_prefix(const string &_Word)29 {30 Node *p = this;31 int i = 0;32 for (; i < _Word.size(); ++i)33 {34 char curr = _Word[i];35 if (p->children.find(curr) == p->children.end())36 {37 if (p->is_word)return true;38 else return false;39 }40 else41 {42 p = p->children[curr];43 }44 }45 return false;46 }47 };
用雜湊演算法最佳化字典樹空間結構