-
Notifications
You must be signed in to change notification settings - Fork 1
/
suffixtree.cpp
115 lines (94 loc) · 2.66 KB
/
suffixtree.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
115
// {"category": "Algorithm", "notes": "Search string for smaller strings"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <vector>
#include <map>
#include <memory>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Given a string s and an array of smaller strings T, design a method to
// search s for each small string in T.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
class SuffixTreeNode
{
public:
SuffixTreeNode() : m_value('\0') {}
SuffixTreeNode(string str)
: m_value('\0')
{
for (string::size_type i = 0; i < str.length(); i++)
{
this->Insert(str.substr(i), i);
}
}
void Insert(string str, int index)
{
m_indexes.push_back(index);
if (!str.empty())
{
m_value = str[0];
shared_ptr<SuffixTreeNode> spChild = m_children[m_value];
if (nullptr == spChild)
{
spChild = shared_ptr<SuffixTreeNode>(new SuffixTreeNode());
m_children[m_value] = spChild;
}
spChild->Insert(str.substr(1), index);
}
}
vector<int> Search(string str)
{
if (str.empty())
{
return m_indexes;
}
shared_ptr<SuffixTreeNode> spChild = m_children[str[0]];
if (spChild != nullptr)
{
return spChild->Search(str.substr(1));
}
return vector<int>();
}
private:
char m_value;
vector<int> m_indexes;
map<char, shared_ptr<SuffixTreeNode>> m_children;
};
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
SuffixTreeNode root(string("bibs"));
char* t[] = { "b", "i", "s", "bi", "ib", "bs", "bib", "ibs", "bibs", "x" };
for (int i = 0; i < ARRAYSIZE(t); i++)
{
vector<int> indexes = root.Search(string(t[i]));
cout << "\"" << t[i] << "\" is ";
if (indexes.size() > 0)
{
for (vector<int>::size_type j = 0; j < indexes.size(); j++)
{
cout << (0 == j ? "at " : ", ") << indexes[j];
}
}
else
{
cout << "not found";
}
cout << endl;
}
return 0;
}