-
Notifications
You must be signed in to change notification settings - Fork 74
/
trie_matching_extended.py
70 lines (57 loc) · 1.57 KB
/
trie_matching_extended.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
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
# python3
import sys
def build_trie(patterns):
tree = dict()
tree[0] = {}
index = 1
for pattern in patterns:
current = tree[0]
for letter in pattern:
if letter in current:
current = tree[current[letter]]
else:
current[letter] = index
tree[index] = {}
current = tree[index]
index = index + 1
current['$'] = {}
return tree
def prefix_trie_matching(text, trie, external_idx):
idx = 0
symbol = text[idx]
current = trie[0]
res = -1
while True:
if not current:
return res
if '$' in current:
return res
if symbol in current:
current = trie[current[symbol]]
res = external_idx
idx += 1
if idx < len(text):
symbol = text[idx]
elif '$' in current:
return res
else:
symbol = '@'
res = -1
else:
return res if '$' in current else -1
def solve(text, n, patterns):
result = set()
trie = build_trie(patterns)
n = len(text)
for i in range(n):
value = prefix_trie_matching(text[i:], trie, i)
if value != -1:
result.add(value)
return sorted(list(result))
text = sys.stdin.readline().strip()
n = int(sys.stdin.readline().strip())
patterns = []
for i in range(n):
patterns += [sys.stdin.readline().strip()]
ans = solve(text, n, patterns)
sys.stdout.write(' '.join(map(str, ans)) + '\n')