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;
    }
    
  • 相关阅读:
    设计算法,求AB两个整数集合的交集
    C++函数传递指针面试题
    C++构造函数、析构函数与抛出异常
    c++ 虚函数表解析
    c++ 对象的内存布局
    09 构造函数能调用虚函数吗?
    C++构造函数初始化顺序
    计数排序,基数排序和桶排序
    80 求论坛在线人数
    79 两个整数集合A和B,求其交集
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/7750010.html
Copyright © 2011-2022 走看看