-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuffixTree.h
More file actions
80 lines (66 loc) · 1.48 KB
/
SuffixTree.h
File metadata and controls
80 lines (66 loc) · 1.48 KB
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
#ifndef SFFIX_TREE_H
#define SFFIX_TREE_H
#include <vector>
#include <unordered_map>
class SuffixTreeNode {
public:
//SuffixTreeNode() {}
SuffixTreeNode(/*char c*/): /*value(c),*/ leaf(false) {}
void insert(string str, int index) {
indexes.push_back(index);
if(str.empty()) {
leaf = true;
return;
}
char first = str[0];
SuffixTreeNode *child;
if(children.find(first) != children.end()) {
child = children[first];
} else {
child = new SuffixTreeNode(/*first*/);
children[first] = child;
}
child->insert(str.substr(1), index);
}
std::vector<int> search(string str) {
if(str.empty()) return indexes;
char first = str[0];
if(children.find(first) == children.end()) {
return std::vector<int>();
} else {
return children[first]->search(str.substr(1));
}
}
bool isSuffix(string str) {
if(str.empty()) return leaf;
char first = str[0];
if(children.find(first) == children.end()) {
return false;
} else {
return children[first]->isSuffix(str.substr(1));
}
}
private:
//char value;
bool leaf;
std::vector<int> indexes;
std::unordered_map<char, SuffixTreeNode*> children;
};
class SuffixTree {
public:
SuffixTree(string str) {
root = new SuffixTreeNode();
for(int i = 0; i < str.size()-1; ++i) {
root->insert(str.substr(i), i);
}
}
std::vector<int> search(string str) {
return root->search(str);
}
bool isSuffix(string str) {
return root->isSuffix(str);
}
private:
SuffixTreeNode *root;
};
#endif //SFFIX_TREE_H