zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    笔记0510
    笔记0514
    笔记0521
    GridView专题
    笔记0418
    笔记0516
    笔记0515
    笔记0507
    Python 安装与环境变量配置
    ffmpeg 下载安装和简单应用
  • 原文地址:https://www.cnblogs.com/max88888888/p/5869604.html
Copyright © 2011-2022 走看看