zoukankan      html  css  js  c++  java
  • Trie树检索字符串

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct TrieNode_t
    {
        char data;
        short int end_flag;//字符串完全添加标志位
        struct TrieNode_t* child_node[26];
    } TrieNode;
    
    TrieNode root = { 0 };
    
    //添加字符串到树中
    void InsertString(char a[], int len)
    {
        int i;
        TrieNode *p = &root;
        for (i = 0; i < len; i++)
        {
            int index = a[i] - 'a';
            if (p->child_node[index] == 0)
            {
                TrieNode *p_child = (TrieNode *)malloc(sizeof(struct TrieNode_t));
                if (NULL == p_child)
                {
                    printf("malloc fail
    ");
                    return;
                }
                p_child->data = a[i];
                p->child_node[index] = p_child;
            }
            p = p->child_node[index];
        }
        p->end_flag = 1;
    }
    
    //查询字符串,时间复杂度为O(len)
    int SearchString(TrieNode root, char a[], int len)
    {
        int i;
        TrieNode *p = &root;
        for (i = 0; i < len; i++)
        {
            int index = a[i] - 'a';
            if (p->child_node[index] == 0)
            {
                return -1;
            }
            p = p->child_node[index];
        }
        
        if (p->end_flag == 1)
        {
            return 0;
        }
        else
        {
            return -1;
        }
    }
    
    
    int main()
    {
        char a[10] = "helloworld";
        char b[10] = "gelloworld";
        char c[10] = "helltworld";
        char d[10] = "helloworlr";
        char e[5] = "hello";
        InsertString(a, 10);
        printf("%d
    ", SearchString(root, e, 10));
        return 0;
    }
  • 相关阅读:
    Cookie工具类
    验证工具类
    压缩工具类
    一次外企QQ面试
    利用Referer请求头阻止"盗链"
    servlet中ServletConfig的使用
    jquery插件制作
    jQuery选择器总结(转)
    js文件加载执行顺序
    mysql有关问题之:the security settings could not be applied to
  • 原文地址:https://www.cnblogs.com/zzdbullet/p/10672189.html
Copyright © 2011-2022 走看看