简单Trie

功能: 添加、包含、前缀
最后简单测试

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<sstream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <functional>
using namespace std;

class trie {
public:
	trie() {
		root = new Node();
		size = 0;
	}
	int GetSize() {
		return size;
	}
	void Add(string word) {
		Node* cur = root;
		for (char c:word) {
			if (cur->next->count(c) == 0) {
				cur->next->insert(make_pair(c, new Node()));
			}
			cur = cur->next->at(c);
		}
		if (!cur->isWord) {
			cur->isWord = true;
			size++;
		} 

	}
	bool Contains(string word) {
		Node* cur = root;
		for (char c : word) {
			if (cur->next->count(c) == 0) {
				return false;
			}
			cur = cur->next->at(c);
		}
		return cur->isWord; 
	}

	bool IsPrefix(string prefix) {
		Node* cur = root;
		for (char c : prefix) {
			if (cur->next->count(c) == 0) {
				return false;
			}
			cur = cur->next->at(c);
		}
		return true;
	}



	class Node {
	public:
		bool isWord;
		map<char, Node*>* next;
		Node(bool isWord) {
			this->isWord = isWord;
			next = new map<char, Node*>();
		}
		Node() {
			this->isWord = false;
			next = new map<char, Node*>();
		}
	};
private:
	Node* root;
	int size;
};



int main(void)
{
	ifstream infile("D:\\Desktop\\Clianxi\\C++\\trie\\testfile\\1.Harry Potter and the Sorcerer's Stone.txt");
	if (!infile.is_open()) {
		return -1;
	}
	vector<string> words;
	trie mytrie;
	while (!infile.eof())
	{
		string line,tmp;
		while (infile >> tmp) {
			tmp.erase(0, tmp.find_first_not_of(" "));
			words.push_back(tmp);
			mytrie.Add(tmp);
			//cout << tmp << endl;
		}
	}
	infile.close();
	cout << "___________" << endl;
/*
	for (string i : words) {
		cout << i << endl;
	}*/
	cout << "___________" << endl;
	cout << mytrie.GetSize() << endl;


	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值