• Trie字典树 动态内存


    Trie字典树

     1 #include "stdio.h"
     2 #include "iostream"
     3 #include "malloc.h"
     4 #include "string.h"
     5 
     6 using namespace std;
     7 
     8 #define MAX_SIZE 26
     9 
    10 typedef struct Trie{
    11     char val;
    12     bool isword;
    13     struct Trie* child[MAX_SIZE];
    14 }Node,*Trie_pointer;
    15 
    16 Trie_pointer CreateNode()
    17 {
    18     Trie_pointer node;
    19     node = (Trie_pointer)malloc(sizeof(Node));
    20     memset(node,0,sizeof(0));
    21     return node;
    22 }
    23 
    24 void Insert(Trie_pointer root, char *s)
    25 {
    26     Trie_pointer tmp,t = root;
    27     char *p = s;
    28     if(*s == '')
    29         return;
    30     while(*p != '')
    31     {
    32         if(t->child[*p - 'a'] == NULL)
    33         {
    34             tmp = CreateNode();
    35             tmp->val = *p;
    36             t->child[*p - 'a'] = tmp;
    37         }
    38         t = t->child[*p - 'a'];
    39         p++;
    40     }
    41     t->isword = 1;
    42 }
    43 
    44 bool Search(Node root, char *s)
    45 {
    46     Trie_pointer t = &root;
    47     char *p = s;
    48     if(*s == '')
    49         return false;
    50     while(*p != '')
    51     {
    52         if(t->child[*p - 'a'] == NULL)
    53             return false;
    54         t = t->child[*p - 'a'];
    55         p++;
    56     }
    57     if(t->isword == 0)
    58         return false;
    59     return true;
    60 }
    61 
    62 int main()
    63 {
    64     Node root;
    65     char s[20];
    66     int i,n;
    67     memset(&root,0,sizeof(Node));
    68     cin>>n;
    69     for(i=1; i<=n; i++)
    70     {
    71         cin>>s;
    72         Insert(&root,s);
    73     }
    74     while(cin>>s)
    75     {
    76         int flag = Search(root,s);
    77         if(flag)
    78             printf("YES
    ");
    79         else
    80             printf("NO
    ");
    81     }
    82     return 0;
    83 }
  • 相关阅读:
    游戏引擎服务端应该也要具备测试模块
    My Trap For C++
    unix网络编程--锁(一)
    所遇不良设计(四)
    所遇不良设计(二)
    有趣的emacs
    [Java复习]Hashcode
    [Java复习]java线程
    [Java复习]重载、覆盖、继承、多态
    折磨我两天的坑!小程序云函数调用时本地和云端测试成功,控制台接收不到正确结果
  • 原文地址:https://www.cnblogs.com/max88888888/p/5869604.html
Copyright © 2020-2023  润新知