-
Notifications
You must be signed in to change notification settings - Fork 0
/
TST.cpp
115 lines (95 loc) · 2.54 KB
/
TST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//
// Created by ahmad on 12/16/16.
//
#include "TST.h"
#include <algorithm>
#include <iostream>
TSTNode::TSTNode(char chr)
{
this->chr = chr;
this->biggerChild = nullptr;
this->selfChild = nullptr;
this->smallerChild = nullptr;
this->isWord = false;
}
TST::TST(bool caseSensivity)
{
isCaseSensitive = caseSensivity;
this->root = nullptr;
}
void TST::add(std::string word)
{
using namespace std;
if (!isCaseSensitive)
std::transform(word.begin(), word.end(), word.begin(), ::tolower);
TSTNode *pointer;
if(!this->root)
{
this->root = new TSTNode(word[0]);
pointer = this->root;
for (int i = 1; i < word.size(); ++i) {
pointer->selfChild = new TSTNode(word[i]);
pointer = pointer->selfChild;
}
}
else
{
int i = 0;
pointer = this->root;
char chrWord;
for (; i < word.size() - 1;) {
chrWord = word[i];
if (chrWord < pointer->chr) {
if (!pointer->smallerChild)
pointer->smallerChild = new TSTNode(chrWord);
pointer = pointer->smallerChild;
} else if (chrWord > pointer->chr) {
if (!pointer->biggerChild)
pointer->biggerChild = new TSTNode(chrWord);
pointer = pointer->biggerChild;
} else {
if (!pointer->selfChild)
pointer->selfChild = new TSTNode(word[i + 1]);
pointer = pointer->selfChild;
i++;
}
}
}
pointer->isWord = true;
}
bool TST::isExisted(std::string word)
{
if (!isCaseSensitive)
std::transform(word.begin(), word.end(), word.begin(), ::tolower);
int i = 0;
if(!this->root)
return false;
TSTNode *pointer = this->root;
char chrWord;
for (; i < word.size() - 1;) {
chrWord = word[i];
if(chrWord < pointer->chr)
{
if (!pointer->smallerChild)
return false;
else
pointer = pointer->smallerChild;
}
else if(chrWord > pointer->chr)
{
if (!pointer->biggerChild)
return false;
pointer = pointer->biggerChild;
}
else
{
if(! pointer->selfChild)
return false;
// if(pointer->selfChild->chr != chrWord)
// return false;
pointer = pointer->selfChild;
i++;
}
}
return pointer->isWord;
}