码迷,mamicode.com
首页 > 其他好文 > 详细

Algorithms(字典树)

时间:2014-05-16 02:52:23      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:字典树

字典树

#ifndef TIRE_H_INCLUDED
#define TIRE_H_INCLUDED


/*
** 字典树
*/
#define MAX 26


typedef struct Node
{
    int num;
    struct Node* next[MAX];
}Tire;



/*
** 创建一个节点
*/
Tire* create(void);


/*
** 插入一个字符串
*/
Tire* insert(char str[], Tire* head);


/*
** 搜索字符串
*/
int search(char str[], Tire* head);


#endif // TIRE_H_INCLUDED

/*----------------------------------------------------------------------------------
 * Project: Tire.cpp
 * Name: zwp
 * Date: 2014/5
 *---------------------------------------------------------------------------------*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Tire.h"
#include <malloc.h>



/*
** 创建一个节点
*/
Tire* create(void)
{
    int i;

    Tire* node = (Tire*)malloc(sizeof(Tire));
    if(node == NULL)
        printf("Out of space...\n");

    /* 初始化 */
    for(i = 0; i < MAX; ++ i)
        node->next[i] = NULL;
    node->num = 0;

    return node;
}


/*
** 插入一个字符串
*/
Tire* insert(char str[], Tire* head)
{
        int i, len = strlen(str);
        Tire *node, *ptr = head;

        for(i = 1; i < len; ++ i)
        {
            int count = str[i] - 'a';
            /* 若不存在该字符串 */
            if(ptr->next[count] == NULL)
            {
                node = create();
                ptr->next[count] = node;
                ptr->num++;
                ptr = ptr->next[count];
            }
            /* 若存在该字符串 */
            else
            {
                ptr = ptr->next[count];
            }
        }
}



/*
** 搜索字符串,返回该字符串出现的次数
*/
int search(char str[], Tire* head)
{
    Tire* ptr = head;
    int len = strlen(str);
    int i, count = 0;

    for(i = 0; i < len; ++ i)
    {

        int cou = str[i] - 'a';
        if(ptr->next[cou] == NULL)
        {
            printf("不存在该字符串\n");
            count = 0;
            return 0;
        }
        else
        {
            ptr = ptr->next[cou];
            count = ptr->num;
        }
    }
    return count;

}










/*------------------------------------------------------------------------------
 * Project: Main.cpp
 * Name: zwp
 * Date: 20145/
 *------------------------------------------------------------------------------*/



 #include "Tire.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>



 int main(int argc, char* argv[])
 {

    Tire* node = create();
    char str[10];

    while(scanf("%s\n", str) )
    {
       if(strcmp(str, "quit") == 0)
            break;
        insert(str, node);

    }


    int count = search("a", node);
    printf("%d\n", count);



     system("pause");
     return 0;

 }


Algorithms(字典树),布布扣,bubuko.com

Algorithms(字典树)

标签:字典树

原文地址:http://blog.csdn.net/qqzwp/article/details/25920813

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!