tire树

#pragma once 

#include <string>
using namespace std;
#define MAX_CHAR 26

struct node 
{
	bool isWord;
	node* next[MAX_CHAR];

	node()
	{
		isWord = false;
		for(int i = 0;i<MAX_CHAR;i++)
			next[i] = NULL;
	}
};

class Tire
{
public:
	Tire(){root = NULL;}

	void insert(string& str)
	{
		if(!root)
			root = new node;

		node* location = root;
		for(int i = 0;i< (int)str.length();i++)
		{
			int num = str[i] - 'a';
			if(!location->next[num])
			{
				location->next[num] = new node;
			}
			location = location->next[num];
		}
		location->isWord = true;
	}

	bool search(string& str)
	{
		if(!root) return false;
		node* location = root;

		for (int i = 0;i<(int)str.length();i++)
		{
			int num = str[i] - 'a';
			if(!location->next[num])
				return false;
			location = location->next[num];
		}
		return location->isWord;
	}
public:
	node* root;
};

 

posted on 2014-11-11 15:07  kangbry  阅读(131)  评论(0编辑  收藏  举报

导航