功能: 添加、包含、前缀
最后简单测试
#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;
}