字典树

来源:互联网 发布:ubuntu17.10安装软件 编辑:程序博客网 时间:2024/05/01 22:39
字典树。
一种数据结构。
简单是挺简单的 但是这种东西就是容易出错。。一定是写的少了
下次写算法一定不要先参看了。。看过之后心思都被阻塞了。。
先来个c++的:
</pre><pre name="code" class="cpp"><pre name="code" class="cpp">#include<iostream>using namespace std;/*暂只记26个字母(a-z)所以可以非常方便的用0-25表示a-z的存在情况只用bool型记录即可*/const int MAX = 26;struct node{bool isWord;node *next[MAX];node(){isWord=false;for(int i=0;i<MAX;i++)next[i]=NULL;}};class Trie{public:node *root;Trie(){root=new node();};void create(string s){node *p=root;for(int i=0;i<s.length();i++)          {              int num = s[i] - 'a';              if(p->next[num] == NULL)              {                  p->next[num] = new node();  p->isWord = true;             }              p = p->next[num];          }               }  bool search(string s)      {          node *p = root;          for(int i=0;i<s.length();i++)          {              int num = s[i] - 'a';              if(p->next[num] == NULL)                  return false;              p = p->next[num];          }          return p->isWord;      }
</pre><pre name="code" class="cpp">};int main(){Trie s;s.create("adds");cout<<s.search("add")<<endl;return 0;}
</pre><pre>
python的一会补上...
<Python:
<pre name="code" class="python">#coding:utf8class node:    def __init__(self):        self.word=None        self.next=[]class Trie:    def __init__(self):        self.root=node()    def create(self,s):        head=self.root.next        for i in s:            if head== []:                mid=node()                mid.word=i                head.append(mid)                head=head[0].next    def search(self,s):        head=self.root.next        for i in s:            if head!= []:                if i == head[0].word:                    head=head[0].next                else:                    return 0            else:                return 0        return 1    


对比一下可以轻松发现
python天生的泛型对这种东西的处理非常方便
python的字典树是可以存储任意符号的而c++只好明确定义~(至少在这里是这样).
0 0