用雜湊演算法最佳化字典樹空間結構

來源:互聯網
上載者:User

標籤: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 };

 

用雜湊演算法最佳化字典樹空間結構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.