#include <iostream>
#include <vector>
using namespace std;
class Node {
private:
char content ;
bool mark ;
vector<Node*> children;
public:
Node();
~Node();
char getContent();
void setContent(char c);
bool isMark();
void setMark(bool b);
Node* findChild(char c);
void appendChild(Node* child);
vector<Node*> getChildren();
};
Node::Node(){
content = ' ';
mark = false ;
}
Node::~Node(){
}
char Node::getContent(){
return content ;
}
void Node::setContent(char c){
content = c ;
}
bool Node::isMark(){
return mark ;
}
void Node::setMark(bool b){
mark = b ;
}
Node* Node::findChild(char c)
{
for ( int i = 0; i < children.size(); i++ ){
Node* temp = children.at(i);
if ( temp->getContent() == c ){
return temp;
}
}
return NULL;
}
void Node::appendChild(Node* child){
children.push_back(child);
}
vector<Node*> Node::getChildren(){
return children;
}
class Trie {
public:
Trie();
~Trie();
void addWord(string s);
bool searchWord(string s);
void deleteWord(string s);
private:
Node* root;
};
Trie::Trie(){
root = new Node() ;
}
Trie::~Trie(){
}
void Trie::addWord(string s)
{
Node* current = root ;
if ( s.length() == 0 ){
current->setMark(true);
return;
}
for ( int i = 0; i < s.length(); i++ ){
Node* child = current->findChild(s[i]);
if ( child != NULL ){
current = child;
}
else{
Node* tmp = new Node();
tmp->setContent(s[i]);
current->appendChild(tmp);
current = tmp;
}
if ( i == s.length() - 1 ){
current->setMark(true);
}
}
}
bool Trie::searchWord(string s)
{
Node* current = root;
while ( current != NULL ){
for ( int i = 0; i < s.length(); i++ ){
Node* tmp = current->findChild(s[i]);
if ( tmp == NULL )
return false;
current = tmp;
}
if ( current->isMark() )
return true;
else
return false;
}
return false;
}
void Trie::deleteWord(string s)
{
Node* current = root ;
while ( current != NULL ){
for ( int i = 0; i < s.length(); i++ ){
Node* tmp = current->findChild(s[i]);
if ( tmp == NULL )
return ;
current = tmp;
}
if ( current->isMark() )
current->setMark(false);
else
return ;
}
return ;
}
int main()
{
Trie* trie = new Trie();
trie->addWord("Jeno5980515");
if ( trie->searchWord("Jeno5980515") )
cout << "Yes Jeno5980515" << endl ;
else
cout << "No Jeno5980515" << endl ;
if ( trie->searchWord("Jeno") )
cout << "Yes Jeno" << endl ;
else
cout << "No Jeno" << endl ;
if ( trie->searchWord("5980515") )
cout << "Yes 5980515" << endl ;
else
cout << "No 5980515" << endl ;
trie->deleteWord("Jeno5980515");
if ( trie->searchWord("Jeno5980515") )
cout << "Yes Jeno5980515" << endl ;
else
cout << "No Jeno5980515" << endl ;
if ( trie->searchWord("Jeno") )
cout << "Yes Jeno" << endl ;
else
cout << "No Jeno" << endl ;
if ( trie->searchWord("5980515") )
cout << "Yes 5980515" << endl ;
else
cout << "No 5980515" << endl ;
delete trie;
return 0 ;
}