God left practice with algorithms (prefix tree) together

What is the prefix tree, how to generate a prefix tree?
Here Insert Picture Description
Here Insert Picture Description
So look for the number of times a string appear in a long string array when it will be very fast. Cut the string end is represented by the number of times the string appear in an array
of one element into the prefix tree process:
Here Insert Picture Description
If you want to deposit other than English characters, but the characters, it does not need an array of pointers, and can engage in a map store to
find in a prefix tree:
Here Insert Picture Description
roughly the code looks like this:

class TrieNode
{
public:
	TrieNode()
		:pass(0)
		, end(0)
	{
		*next = new TrieNode[26];
	}
	int pass;
	int end;
	TrieNode** next = nullptr;   //这里真的是太恶心了,找了半天的错误
};
TrieNode* p = nullptr;
class Trie
{
public:
	Trie()
		:root(new TrieNode())  //先构造一个前缀树的根节点
	{}
	void Insert(string str)  //准备将字符串str插入前缀树
	{
		if (str.empty())
			return;
		TrieNode* Node = root;  //一个指针指向头结点,开始根据字符串往下遍历
		int index = 0;
		for (int i = 0; i < str.size(); ++i)
		{
			index = str[i] - 'a';  
			//拿到索引值,加入第一个字符是'b',减'a'之后就等于1,
			//那么就说明要找root节点中的那个26个指针的数组中的1号索引是否被创建,
			//创建了的话就直接沿着创建好的节点走,没有的话就创建
			if (Node->next[index] == nullptr)  //就代表此时还没有这个结点
			{
				Node->next[index] = new TrieNode;
			}
			Node = Node->next[index];//跑到这个结点继续往下找看存不存在接下来元素的节点
			Node->pass++;
		}
		Node->end++;
	}
	int Search(string str)  //查找
	{
		if (str.empty())
			return 0;
		TrieNode* Node = root;
		int index = 0;
		for (int i = 0; i < str.size(); ++i)
		{
			index = str[i] - 'a';
			if (Node->next[index] == nullptr)
				return 0;
			Node = Node->next[index];
		}
		return Node->end;
	}
	void Delete(string str)  //删除一个str,假如存在多个str的话,这个函数的功能就是删除一个str
	{
		if (Search(str) == 0)  //如果根本就不存在这个字符串那么久不用删除了
			return;
		TrieNode* Node = root;
		//Node->pass--;
		int index = 0;
		int i;
		for (i = 0; i < str.size(); ++i)  //下面这一大坨自己写的,我感觉主要就是因为C++的new出来的内存需要手动释放引起的
		{
			index = str[i] - 'a';
			if (--Node->next[index]->pass == 0)
			{
				TrieNode* cur = Node->next[index];
				Node->next[index] = nullptr;
				Node = cur;
				i++;
				break;
			}
		}
		while (i < str.size())
		{
			TrieNode* cur = Node->next[index];
			delete Node;
			Node = cur;
			++i;
		}
		Node->end--;
	}
private:
	TrieNode* root;
};
Published 230 original articles · won praise 28 · views 9325

Guess you like

Origin blog.csdn.net/weixin_43767691/article/details/103425764