C++实现简易Trie树

放码过来

#include <iostream>
#include <string>
using namespace std;

struct TrieNode
{
	char data;
	TrieNode *children[26];
	bool isEndingChar;
	TrieNode(char data): data(data), isEndingChar(false) 
	{
		for (int i = 0; i < 26; ++i)
			children[i] = nullptr;
	}
};

class Trie
{
private:
	TrieNode *root = new TrieNode('/');
public:
	void insert(string str)
	{
		TrieNode *p = root;
		for (int i = 0; i < str.size(); ++i)
		{
			int index = str[i] - 'a';
			if (p->children[index] == nullptr)
			{
				TrieNode *newNode = new TrieNode(str[i]);
				p->children[index] = newNode;
			}
			p = p->children[index];
		}
		p->isEndingChar = true;
	}

	bool find(string str)
	{
		TrieNode *p = root;
		for (int i = 0; i < str.size(); ++i)
		{
			int index = str[i] - 'a';
			if (p->children[index] == nullptr)
				return false;
			p = p->children[index];
		}
		if (p->isEndingChar == false)
			return false;
		else
			return true;
	}
};

int main()
{
	Trie myTrie;
	myTrie.insert("hello");
	myTrie.insert("tlq");
	myTrie.insert("xsq");

	if (myTrie.find("hello"))
	{
		cout << "myTrie has string of [hello]" << endl;
	}
	if (myTrie.find("tlq"))
	{
		cout << "myTrie has string of [tlq]" << endl;
	}
	if (myTrie.find("xsq"))
	{
		cout << "myTrie has string of [xsq]" << endl;
	}
	if (myTrie.find("balabala"))
	{
		cout << "myTrie has string of [hello]" << endl;
	}
	else
	{
		cout << "myTrie don't have string of [balabala]" << endl;
	}
	return 0;
}
发布了37 篇原创文章 · 获赞 42 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42570248/article/details/101173185
今日推荐