-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsuffixtree.cc
71 lines (59 loc) · 1.47 KB
/
suffixtree.cc
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
/*
An implementation of Ukkonen's O(n) online suffix tree algorithm,
http://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
clang -Wall -o suffixtree -O2 suffixtree.cc
*/
#include <err.h>
#include <stdio.h>
#include <string.h>
#include <sysexits.h>
struct Node {
Node() {
memset(next, 0, sizeof(next));
suffix = 0;
}
Node* next[256];
Node* suffix;
};
int main(int argc, char* argv[]) {
if (argc < 2)
errx(EX_USAGE, "usage: %s string [strings...]", argv[0]);
const char* input = argv[1];
/* Build suffix trie, algorithm 1 */
Node bottom;
Node root;
for (int i = 0; i < 256; ++i)
bottom.next[i] = &root;
root.suffix = ⊥
Node* top = &root;
for (int i = 0, n = strlen(input); i < n; ++i) {
int ti = input[i];
Node* r = top;
Node* oldrp = 0;
while (!r->next[ti]) {
Node* rp = new Node;
r->next[ti] = rp;
if (r != top)
oldrp->suffix = rp;
oldrp = rp;
r = r->suffix;
}
oldrp->suffix = r->next[ti];
top = top->next[ti];
}
/* Build suffix tree. */
/* Lame application: For each further argument, print if it's a substring
* of the original string. */
for (int i = 2; i < argc; ++i) {
Node* r = &root;
const char* s = argv[i];
bool prefix_of_suffix = true;
for (int j = 0, n = strlen(s); r && j < n; ++j) {
r = r->next[(int)s[j]];
if (!r)
prefix_of_suffix = false;
}
if (prefix_of_suffix)
printf("%s\n", argv[i]);
}
}