• [搜索]Trie树的实现


    trie这种树也被称为线索,搜索树。

    正如图

    以下是用stl 的map来实现

    class trie_item_c
    {
    public:
    	trie_item_c(){}
    	trie_item_c(const char nm)
    	{
    		name = nm;
    	}
    	
    	void set_name(const char nm)
    	{
    		name = nm;
    	}
    	
    	trie_item_c * get_child(const char nm)
    	{
    		map<const char ,trie_item_c*>::const_iterator it = children.find(nm);
    		if(it != children.end())
    			return it->second;
    		else
    		{
    			trie_item_c *cld = new trie_item_c(nm);
    			children.insert(pair <const char ,trie_item_c*>(nm,cld));
    			return cld;
    		}
    	}
    	bool find(const char* dic)
    	{
    		if(!dic || *dic == '')
    		{
    			if(children.end() != children.find(''))
    				return true;
    			return false;
    		}
    		const char* temp = dic;
    		map<const char ,trie_item_c*>::const_iterator it = children.find(*temp);
    		if(it == children.end())
    			return false;
    		return it->second->find(++temp);
    	}
    	void print()
    	{
    		printf("%c",name);
    		map<const char ,trie_item_c*>::const_iterator it = children.begin();
    		for(;it != children.end();it++)
    		{
    			it->second->print();
    		}
    		printf("
    ");
    	}
    	virtual ~trie_item_c()
    	{
    		map<const char ,trie_item_c*>::const_iterator it = children.begin();
    		while(it != children.end())
    		{
    			delete it->second;
    			children.erase(it);
    			it = children.begin();
    		}
    	}
    private:
    	map<const char ,trie_item_c*> children;
    	char name;
    
    };

    以下代码是构建树的过程

    for(const char* dic = lst.first_string();dic;dic = lst.next_string())
    	{
    		
    		trie_item_c *temp = root;
    		for(int i=0;i<str_temp.str_len();i++)
    		{
    			char c = str_temp.get(i);
    			trie_item_c *item = temp->get_child(c);
    			temp = item;
    		}
    		//add one null child
    		temp->get_child('');
    	}

    推断是否一个字root在,只需要调用root->find("book");您可以。

    
  • 相关阅读:
    移动硬盘文件被恶意隐藏
    asp.net identity UserSecurityStamp 的作用
    Head First Python学习笔记1
    WPF 确认动态加载数据完成
    rust by example 2
    Rust by Example1
    奇葩!把类型转成object
    Lambda高手之路第一部分
    理解Lambda表达式
    贪心算法-找零钱(C#实现)
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5047897.html
Copyright © 2020-2023  润新知