-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsuffix_tree.py
37 lines (32 loc) · 1.06 KB
/
suffix_tree.py
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
class Node:
def __init__(self):
self.children = {}
self.start_index = None
self.end_index = None
class SuffixTree:
def __init__(self, string):
self.string = string
self.root = Node()
self.build_tree()
def build_tree(self):
n = len(self.string)
for i in range(n):
current = self.root
for j in range(i, n):
if self.string[j] not in current.children:
node = Node()
node.start_index = j
current.children[self.string[j]] = node
current = node
else:
current = current.children[self.string[j]]
current.end_index = j
def search(self, pattern):
current = self.root
for char in pattern:
if char not in current.children:
return False
current = current.children[char]
return True
suffix_tree = SuffixTree('banana')
print(suffix_tree.search('ana')) #returns true or false