zoukankan      html  css  js  c++  java
  • [算法] trie树实现

    小写字母的字典树

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXN 1000
    #define LEN 100
    
    char END[LEN] = "0";
    
    struct node{
        struct node* next[26];    
        int id;
        int end;    
    };
    
    int count;
    char book[MAXN][LEN];
    struct node root;
    
    int isin(struct node *root, char *tmp) {
        char head;
        if(tmp[0] == '') {
            if(root->end == 1) {
                return 1;
            }
            else {
                return 0;     
            }
        } 
        head = *(char *)tmp - 'a';
        if(root->next[head] == NULL) {
            return 0;  
        }
        return isin(root->next[head], tmp + 1);
    }
    
    
    void insert(struct node *root, char *tmp)
    {
        struct node *t;
        if(tmp[0] == '') {
            root->end = 1;
            root->id = count;
            return;
        }
        t = (struct node *)malloc(sizeof(struct node));
        t->id = -1;
        t->end = 0;
        memset(t->next, 0, sizeof(t->next));
        root->next[*(char *)tmp - 'a'] = t;
        insert(t, tmp + 1);
        return;
    }
    
    int main() {
        
        /* init */
        char tmp[LEN];
        int i;
        count = 0;
        memset(book, 0, sizeof(book));
        root.id = -1;
        root.end = 0;
        memset(root.next, 0, sizeof(root.next));
    
        while(1) {
            scanf("%s", tmp);     
            if(strcmp(tmp, END) == 0) {
                break;     
            }
            if(isin(&root, tmp) == 1) {
                printf("already in
    ");     
            }
            else {
                strcpy(book[count], tmp);
                insert(&root, tmp);
                count ++;
            }
        }
        printf("now we have %d words:
    ", count);
        for(i = 0; i < count; i++) {
            printf("%s
    ", book[i]);    
        }
        return 0;    
    }
    

      

  • 相关阅读:
    Android 查看通讯录Contacts是否发生变化
    卓尼斯ZT-180评測
    C++中的单例模式
    Android 动画之ScaleAnimation应用具体解释
    java的静态代理
    词性标注
    ubuntu 11.04安装笔记
    机房收费系统学生下机结账小结
    MyBatis入门学习(一)
    !!!!OpenWrt系列教程汇总
  • 原文地址:https://www.cnblogs.com/igloo1986/p/3521388.html
Copyright © 2011-2022 走看看