zoukankan      html  css  js  c++  java
  • 字典树模版

    #define MAX 26
    
    typedef struct Node
    {
    	struct Node *next[MAX];
    	int v;
    }Node, *Trie;
    Trie root;
    
    void createTrie(char *str)
    {
    	int len, i, j;
    	Node *current, *newnode;
    	len = strlen(str);
    	if(len == 0)
    	{
    		return;
    	}
    	current = root;
    	for(i = 0; i < len; i++)
    	{
    		int id = str[i] - 'a';
    		if(current->next[id] == NULL)
    		{
    			newnode = (Trie)malloc(sizeof(Node));
    			newnode->v = 1;    //初始v==1
    			for(j = 0; j < MAX; j++)
    			{
    				newnode->next[j] = NULL;
    			}
    			current->next[id] = newnode;
    			current = current->next[id];
    		}
    		else
    		{
    			current->next[id]->v++;
    			current = current->next[id];
    		}
    	}
    }
    
    int findTrie(char *str)
    {
    	int i, len;
    	Trie current = root;
    	len = strlen(str);
    	if(len == 0)
    	{
    		return 0;
    	}
    	for(i = 0; i < len; i++)
    	{
    		int id = str[i] - 'a';  //根据需要选择是减去'0'还是'a',或者是'A'
    		current = current->next[id];
    		if(current == NULL)   //若为空集,表示不存以此为前缀的串
    		{
    			return 0;
    		}
    	}
    	return -1;   //此串是字符集中某串的前缀
    	//return current->v;
    }
    
    void dealTrie(Trie T)
    {
    	int i;
    	if(T == NULL)
    	{
    		return;
    	}
    	for(i = 0; i < MAX; i++)
    	{
    		if(T->next[i] != NULL)
    		{
    			dealTrie(T->next[i]);
    		}
    	}
    	free(T);
    	T = NULL;
    }
    

    而对于静态建立:

    int cnt = 0;
    Node node[10000];
    node[cnt].v = 1;
    for (int i = 0; i < MAX; i++)
    {
    	node[cnt].next[i] = NULL;
    }  
    current->next[id] = &node[cnt++];




  • 相关阅读:
    华为云发送邮件
    activiti act_re_model 分析
    tengine upstream
    zuul压力测试与调优
    idea 快捷键
    kubernetes helm
    编写高质量代码–改善python程序的建议(二)
    编写高质量代码--改善python程序的建议(一)
    总结OpenvSwitch的调试经验
    提高SDN控制器拓扑发现性能
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835065.html
Copyright © 2011-2022 走看看