-
-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathsuffix_automaton.py
More file actions
177 lines (146 loc) · 5.13 KB
/
Copy pathsuffix_automaton.py
File metadata and controls
177 lines (146 loc) · 5.13 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""
Suffix Automaton (SAM) for String Processing.
Reference: https://en.wikipedia.org/wiki/Suffix_automaton
Reference: https://cp-algorithms.com/string/suffix-automaton.html
A Suffix Automaton is the minimal Deterministic Finite Automaton (DFA) that recognizes
all suffixes (and substrings) of a given string in O(N) time and O(N) space.
"""
from dataclasses import dataclass, field
@dataclass
class State:
"""
State (node) in a Suffix Automaton.
"""
length: int = 0
link: int = -1
next: dict[str, int] = field(default_factory=dict)
class SuffixAutomaton:
"""
Suffix Automaton data structure.
>>> sam = SuffixAutomaton("abacaba")
>>> sam.contains("abac")
True
>>> sam.contains("caba")
True
>>> sam.contains("xyz")
False
>>> sam.count_distinct_substrings()
21
>>> sam.count_occurrences("aba")
2
>>> sam.count_occurrences("a")
4
>>> SuffixAutomaton("")
Traceback (most recent call last):
...
ValueError: Input string must not be empty.
"""
def __init__(self, string: str) -> None:
if not string:
raise ValueError("Input string must not be empty.")
self.states: list[State] = [State(length=0, link=-1)]
self.last: int = 0
self.string: str = string
for char in string:
self.extend(char)
def extend(self, char: str) -> None:
"""
Extend the Suffix Automaton by appending character char.
Time Complexity: O(1) amortized
"""
curr = len(self.states)
self.states.append(State(length=self.states[self.last].length + 1))
prev_state = self.last
while prev_state != -1 and char not in self.states[prev_state].next:
self.states[prev_state].next[char] = curr
prev_state = self.states[prev_state].link
if prev_state == -1:
self.states[curr].link = 0
else:
next_state = self.states[prev_state].next[char]
if self.states[prev_state].length + 1 == self.states[next_state].length:
self.states[curr].link = next_state
else:
clone = len(self.states)
self.states.append(
State(
length=self.states[prev_state].length + 1,
link=self.states[next_state].link,
)
)
self.states[clone].next = dict(self.states[next_state].next)
while (
prev_state != -1
and self.states[prev_state].next.get(char) == next_state
):
self.states[prev_state].next[char] = clone
prev_state = self.states[prev_state].link
self.states[next_state].link = clone
self.states[curr].link = clone
self.last = curr
def contains(self, pattern: str) -> bool:
"""
Check if pattern exists as a substring in O(|pattern|) time.
>>> sam = SuffixAutomaton("banana")
>>> sam.contains("nan")
True
>>> sam.contains("apple")
False
"""
curr = 0
for char in pattern:
if char not in self.states[curr].next:
return False
curr = self.states[curr].next[char]
return True
def count_distinct_substrings(self) -> int:
"""
Compute total number of distinct substrings in O(N) time.
>>> sam = SuffixAutomaton("abc")
>>> sam.count_distinct_substrings()
6
>>> SuffixAutomaton("aaaa").count_distinct_substrings()
4
"""
total = 0
for state in self.states[1:]:
total += state.length - self.states[state.link].length
return total
def count_occurrences(self, pattern: str) -> int:
"""
Count occurrences of pattern as a substring in the text in O(N + |pattern|) time
>>> sam = SuffixAutomaton("banana")
>>> sam.count_occurrences("an")
2
>>> sam.count_occurrences("na")
2
>>> sam.count_occurrences("banana")
1
>>> sam.count_occurrences("xyz")
0
"""
curr = 0
for char in pattern:
if char not in self.states[curr].next:
return 0
curr = self.states[curr].next[char]
# Standard endpos size calculation via suffix link tree
occurrences = [0] * len(self.states)
order = sorted(
range(len(self.states)),
key=lambda state_index: self.states[state_index].length,
reverse=True,
)
# Mark initial end positions of prefix states
temp_last = 0
for char in self.string:
temp_last = self.states[temp_last].next[char]
occurrences[temp_last] = 1
# Push endpos sizes up the suffix link tree
for state_index in order:
if self.states[state_index].link != -1:
occurrences[self.states[state_index].link] += occurrences[state_index]
return occurrences[curr]
if __name__ == "__main__":
import doctest
doctest.testmod()