zoukankan      html  css  js  c++  java
  • Trie树

    Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。

    Trie的简单实现(插入、查询)

      

    #include <stdio.h>
    #include <string>
    using namespace std;
    
    const int branchNum = 26;
    
    struct Trie_node
    {
    	bool isStr;
    	Trie_node *next[branchNum];
    	Trie_node()
    	{
    		isStr = false;
    		memset(next, NULL, sizeof(next));
    	}
    };
    
    class Trie
    {
    public:
    	Trie();
    	~Trie();
    	void insert(const char* word);
    	bool search(char* word);
    	void deleteTrie(Trie_node* root);
    
    	Trie_node* root;
    };
    
    Trie::Trie()
    {
    	root = new Trie_node();
    }
    Trie::~Trie()
    {
    	deleteTrie(root);
    }
    void Trie::insert(const char* word)
    {
    	Trie_node *location = root;
    
    	while (*word)
    	{
    		if (location->next[*word - 'a'] == NULL)
    		{
    			location->next[*word - 'a'] = new Trie_node();
    		}
    		
    		location = location->next[*word-'a'];
    		word ++;
    	}
    
    	location->isStr = true;
    }
    
    void Trie::deleteTrie( Trie_node* root )
    {
    	if (root == NULL)
    	{
    		return;
    	}
    
    	for (int i = 0; i < branchNum; i ++)
    	{
    		deleteTrie(root->next[i]);
    	}
    	
    	delete root;
    }
    
    bool Trie::search( char* word )
    {
    	Trie_node *locaton = root;
    
    	while (*word && locaton)
    	{
    		locaton = locaton->next[*word - 'a'];
    		word ++;
    	}
    	
    	return(locaton != NULL && locaton->isStr);
    }
    
    
    int main()
    {
    	Trie trie;
    	trie.insert("helloworld!");
    	trie.insert("he!");
    	trie.insert("helloworlda!");
    
    	if (trie.search("helloworld!"))
    	{
    		printf("true
    ");
    	}
    	return 0;
    }
    
  • 相关阅读:
    进程管理
    linux进程间的通信方式
    linux进程调度的算法
    安装haroopad
    SAE部署Java应用
    Jetty 8.1 安装 运行 部署
    javaweb学习总结(五)——Servlet开发(一)
    eclipse打war包
    Java基础学习总结——Java对象的序列化和反序列化
    Linux学习之CentOS(十三)--CentOS6.4下Mysql数据库的安装与配置
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/7750010.html
Copyright © 2011-2022 走看看