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

    字典树又称单词查找树,Trie树。是一种树形结构,是一种哈希树的变种。典型应用是用于统计。排序和保存大量的字符串(但不仅限于字符串),所以常常被搜索引擎系统用于文本词频统计。

    它的长处是:利用字符串的公共前缀来降低查询时间,最大限度地降低无谓的字符串比較。查询效率比哈希树高。



    它有3个基本性质:
    1.根节点不包括字符,除根节点外每个节点都仅仅包括一个字符; 

    2.从根节点到某一节点,路径上经过的字符连接起来,为该节点相应的字符串;

    3.每一个节点的全部子节点包括的字符都不同样。


    // Trie.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include<iostream>
    
    using namespace std;
    
    #define MAXSIZE 26
    
    
    
    struct TrieNode
    {
    	TrieNode* next[MAXSIZE];
    	char p;
    	int Num;
    	bool isword;
    };
    
    TrieNode*initiate_Trie()
    {
    	TrieNode*root = new TrieNode;
    	for (int i = 0; i < MAXSIZE; i++)
    		root->next[i] = NULL;
    	root->Num = 0;
    	root->isword = false;
    	return root;
    
    
    }
    
    bool search(TrieNode*root, char*str)
    {
    	TrieNode*tn;
    	tn = root;
    	int k;
    	while (*str != '')
    	{
    		k = *str - 'a';
    		if (tn->next[k] == NULL)
    			return false;
    		tn = tn->next[k];
    		str++;
    	}
    	if (tn->isword == false)
    		return false;
    	return true;
    }
    
    TrieNode*build_Trie_singleword(TrieNode*root, char*str)
    {
    	if (search(root, str))
    		return root;
    	root->Num = root->Num + 1;
    	TrieNode*tn;
    	tn = root;
    	while (*str != '')
    	{
    		int k = *str - 'a';
    		if (tn->next[k] == NULL)
    		{
    			tn->next[k] = new TrieNode;
    			for (int i = 0; i < MAXSIZE; i++)
    				tn->next[k]->next[i] = NULL;
    			tn->next[k]->p = *str;
    			tn->next[k]->Num = 1;
    			tn->next[k]->isword = false;
    		}
    
    		else
    		{
    			tn->next[k]->Num = tn->next[k]->Num + 1;
    
    		}
    		tn = tn->next[k];
    		str++;
    	}
    	tn->isword = true;
    	return root;
    }
    
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	TrieNode*root = initiate_Trie();
    	root = build_Trie_singleword(root, "abc");
    	root = build_Trie_singleword(root, "abcd");
    	root = build_Trie_singleword(root, "abc");
    	
    	system("pause");
    	return 0;
    }
    




  • 相关阅读:
    PHP的错误和异常处理
    异步并行批处理框架设计的一些思考
    系统出错信息设计
    SpringMVC+Shiro权限管理
    jstl教程
    为什么Lisp语言如此先进
    「只差程序员」为什么会招黑? [转自:知乎]
    大侠是怎样炼成的 周昆 [转]
    【OpenGL】glFinish()和glFlush()函数详解-[转]
    VC++ 6.0中实现三叉切分窗口与多视图 [转]
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6939523.html
Copyright © 2011-2022 走看看