Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Suffix_Structures.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
48#ifndef SUFFIX_STRUCTURES_H
49#define SUFFIX_STRUCTURES_H
50
51#include <algorithm>
52#include <limits>
53#include <string>
54#include <string_view>
55#include <utility>
56#include <array>
57
58#include <ah-errors.H>
59#include <tpl_array.H>
60#include <tpl_sort_utils.H>
61
62namespace Aleph {
63namespace suffix_structures_detail {
68inline Array<size_t> all_positions(const size_t n)
69{
71 out.reserve(n + 1);
72 for (size_t i = 0; i <= n; ++i)
73 out.append(i);
74 return out;
75}
76
81{
82 introsort(a);
83}
84} // namespace suffix_structures_detail
85
98inline Array<size_t> suffix_array(const std::string_view text)
99{
100 const size_t n = text.size();
101 if (n == 0)
102 return {};
103
106 Array<int> tmp_rank = Array<int>::create(n);
108
109 for (size_t i = 0; i < n; ++i)
110 {
111 sa[i] = i;
112 rank[i] = static_cast<unsigned char>(text[i]);
113 }
114
115 int max_rank = 255; // initial ranks are char codes in [0, 255]
116
117 for (size_t k = 1;;)
118 {
119 auto key2 = [&](const size_t idx) -> int
120 {
121 return (idx + k < n) ? rank[idx + k] : -1;
122 };
123
124 auto key1 = [&](const size_t idx) -> int
125 {
126 return rank[idx];
127 };
128
129 counting_sort_indices(sa, tmp_sa, n, -1, max_rank, key2);
130 counting_sort_indices(sa, tmp_sa, n, 0, max_rank, key1);
131
132 auto less_idx = [&](const size_t a, const size_t b)
133 {
134 if (rank[a] != rank[b])
135 return rank[a] < rank[b];
136 const int ra = (a + k < n) ? rank[a + k] : -1;
137 const int rb = (b + k < n) ? rank[b + k] : -1;
138 return ra < rb;
139 };
140
141 tmp_rank[sa[0]] = 0;
142 for (size_t i = 1; i < n; ++i)
143 tmp_rank[sa[i]] = tmp_rank[sa[i - 1]] + (less_idx(sa[i - 1], sa[i]) ? 1 : 0);
144
145 for (size_t i = 0; i < n; ++i)
146 rank[i] = tmp_rank[i];
147
148 max_rank = rank[sa[n - 1]];
149
150 if (max_rank == static_cast<int>(n - 1))
151 break;
152
153 if (k >= n)
154 break;
155
156 if (k > n / 2)
157 break;
158
159 k *= 2;
160 }
161
162 return sa;
163}
164
183inline Array<size_t> lcp_array_kasai(const std::string_view text, const Array<size_t> &sa)
184{
185 const size_t n = text.size();
186
187 ah_domain_error_if(sa.size() != n) << "lcp_array_kasai(): suffix array size must match text size";
188
189 Array<size_t> lcp;
190 if (n == 0)
191 return lcp;
192
193 lcp = Array<size_t>::create(n);
194 for (size_t i = 0; i < n; ++i)
195 lcp[i] = 0;
196
197 Array<size_t> rank(n, std::numeric_limits<size_t>::max());
198 for (size_t i = 0; i < n; ++i)
199 {
200 ah_out_of_range_error_if(sa[i] >= n)
201 << "lcp_array_kasai(): suffix array contains invalid index";
202 ah_out_of_range_error_if(rank[sa[i]] != std::numeric_limits<size_t>::max())
203 << "lcp_array_kasai(): suffix array contains duplicate index";
204 rank[sa[i]] = i;
205 }
206
207 size_t k = 0;
208 for (size_t i = 0; i < n; ++i)
209 {
210 const size_t r = rank[i];
211 if (r + 1 >= n)
212 {
213 k = 0;
214 continue;
215 }
216
217 const size_t j = sa[r + 1];
218 while (i + k < n and j + k < n and text[i + k] == text[j + k])
219 ++k;
220
221 lcp[r] = k;
222
223 if (k > 0)
224 --k;
225 }
226
227 return lcp;
228}
229
249{
250public:
251 static constexpr size_t npos = std::numeric_limits<size_t>::max();
252
257 struct Node
258 {
259 size_t start = 0;
260 size_t end = 0;
261 size_t parent = npos;
264 };
265
266private:
267 std::string text_;
268 size_t original_size_ = 0;
270
271 static char choose_terminal(const std::string_view s)
272 {
273 std::array<bool, 256> used;
274 used.fill(false);
275 for (const unsigned char c : s)
276 used[c] = true;
277
278 for (size_t i = 0; i < 256; ++i)
279 if (not used[i])
280 return static_cast<char>(i);
281
282 ah_domain_error() << "Naive_Suffix_Tree::choose_terminal(): all 256 byte values "
283 << "are present in the input; no terminal marker available";
284
285 return '\0'; // unreachable
286 }
287
288 size_t create_node(const size_t start, const size_t end, const size_t parent, const size_t suffix_index)
289 {
290 Node n;
291 n.start = start;
292 n.end = end;
293 n.parent = parent;
294 n.suffix_index = suffix_index;
295 nodes_.append(n);
296 return nodes_.size() - 1;
297 }
298
299 size_t find_child_by_first_char(const size_t node, const char c) const
300 {
301 const Array<size_t> &children = nodes_[node].children;
302 for (size_t i = 0; i < children.size(); ++i)
303 if (const size_t child = children[i]; text_[nodes_[child].start] == c)
304 return child;
305
306 return npos;
307 }
308
309 void replace_child(const size_t parent, const size_t old_child, const size_t new_child)
310 {
311 for (Array<size_t> &children = nodes_[parent].children; size_t & i : children)
312 if (i == old_child)
313 {
314 i = new_child;
315 return;
316 }
317 }
318
319 void insert_suffix(const size_t suffix_start)
320 {
321 size_t current = 0;
322 size_t pos = suffix_start;
323
324 while (pos < text_.size())
325 {
326 const size_t child = find_child_by_first_char(current, text_[pos]);
327 if (child == npos)
328 {
329 const size_t leaf = create_node(pos, text_.size(), current, suffix_start);
330 nodes_[current].children.append(leaf);
331 return;
332 }
333
334 const size_t edge_start = nodes_[child].start;
335 const size_t edge_end = nodes_[child].end;
336
337 size_t k = 0;
338 while (pos + k < text_.size() and edge_start + k < edge_end
339 and text_[pos + k] == text_[edge_start + k])
340 ++k;
341
342 if (edge_start + k == edge_end)
343 {
344 current = child;
345 pos += k;
346 continue;
347 }
348
349 const size_t split = create_node(edge_start, edge_start + k, current, npos);
350
351 replace_child(current, child, split);
352
353 nodes_[child].start = edge_start + k;
354 nodes_[child].parent = split;
355 nodes_[split].children.append(child);
356
357 const size_t leaf = create_node(pos + k, text_.size(), split, suffix_start);
358 nodes_[split].children.append(leaf);
359
360 return;
361 }
362 }
363
364 void collect_leaf_suffixes(const size_t node, Array<size_t> &out) const
365 {
366 Array<size_t> stack;
367 stack.append(node);
368
369 while (not stack.is_empty())
370 {
371 const size_t u = stack.remove_last();
372 if (nodes_[u].suffix_index != npos)
373 {
374 if (nodes_[u].suffix_index < original_size_)
375 out.append(nodes_[u].suffix_index);
376 continue;
377 }
378
379 for (const Array<size_t> &children = nodes_[u].children; size_t i : children)
380 stack.append(i);
381 }
382 }
383
384public:
393 explicit Naive_Suffix_Tree(const std::string_view text = "")
394 {
395 build(text);
396 }
397
402 Naive_Suffix_Tree(const Naive_Suffix_Tree &other) = default;
403
417 {
418 swap(other);
419 }
420
427
435 {
436 swap(other);
437 return *this;
438 }
439
443 void swap(Naive_Suffix_Tree &other) noexcept
444 {
445 text_.swap(other.text_);
446 std::swap(original_size_, other.original_size_);
447 nodes_.swap(other.nodes_);
448 }
449
457 void build(const std::string_view text)
458 {
459 const char terminal = choose_terminal(text);
460 std::string new_text(text.begin(), text.end());
461 new_text.push_back(terminal);
462
463 original_size_ = text.size();
464 text_ = std::move(new_text);
465
466 nodes_.empty();
467 nodes_.append(Node{}); // root
468
469 for (size_t i = 0; i < text_.size(); ++i)
470 insert_suffix(i);
471 }
472
481 [[nodiscard]] bool contains(const std::string_view pattern) const
482 {
483 if (pattern.empty())
484 return true;
485
486 size_t current = 0;
487 size_t pos = 0;
488
489 while (pos < pattern.size())
490 {
491 const size_t child = find_child_by_first_char(current, pattern[pos]);
492 if (child == npos)
493 return false;
494
495 const size_t edge_start = nodes_[child].start;
496 const size_t edge_end = nodes_[child].end;
497
498 size_t k = 0;
499 while (pos + k < pattern.size() and edge_start + k < edge_end
500 and text_[edge_start + k] != text_.back() // Never match sentinel
501 and pattern[pos + k] == text_[edge_start + k])
502 ++k;
503
504 if (pos + k == pattern.size())
505 return true;
506
507 if (edge_start + k == edge_end)
508 {
509 current = child;
510 pos += k;
511 continue;
512 }
513
514 return false;
515 }
516
517 return true;
518 }
519
532 [[nodiscard]] Array<size_t> find_all(const std::string_view pattern) const
533 {
534 if (pattern.empty())
536
537 size_t current = 0;
538 size_t pos = 0;
539
540 while (pos < pattern.size())
541 {
542 const size_t child = find_child_by_first_char(current, pattern[pos]);
543 if (child == npos)
544 return {};
545
546 const size_t edge_start = nodes_[child].start;
547 const size_t edge_end = nodes_[child].end;
548
549 size_t k = 0;
550 while (pos + k < pattern.size() and edge_start + k < edge_end
551 and text_[edge_start + k] != text_.back() // Never match sentinel
552 and pattern[pos + k] == text_[edge_start + k])
553 ++k;
554
555 if (pos + k == pattern.size())
556 {
557 Array<size_t> matches;
558 collect_leaf_suffixes(child, matches);
560 return matches;
561 }
562
563 if (edge_start + k == edge_end)
564 {
565 current = child;
566 pos += k;
567 continue;
568 }
569
570 return {};
571 }
572
573 return {};
574 }
575
582 [[nodiscard]] size_t node_count() const noexcept
583 {
584 return nodes_.size();
585 }
586
594 [[nodiscard]] size_t text_size() const noexcept
595 {
596 return original_size_;
597 }
598
605 [[nodiscard]] const Array<Node> &nodes() const noexcept
606 {
607 return nodes_;
608 }
609};
610
623{
624public:
626 struct State
627 {
628 std::array<int, 256> next;
629 int link = -1;
630 size_t len = 0;
631 size_t first_pos = 0;
632 bool terminal = false;
635 {
636 next.fill(-1);
637 }
638 };
639
640private:
642 int last_ = 0;
643
648 {
649 int p = last_;
650 while (p != -1)
651 {
652 states_[static_cast<size_t>(p)].terminal = true;
653 p = states_[static_cast<size_t>(p)].link;
654 }
655 }
656
657public:
664 {
665 clear();
666 }
667
672 Suffix_Automaton(const Suffix_Automaton &other) = default;
673
688 {
689 swap(other);
690 }
691
698
706 {
707 swap(other);
708 return *this;
709 }
710
714 void swap(Suffix_Automaton &other) noexcept
715 {
716 states_.swap(other.states_);
717 std::swap(last_, other.last_);
718 }
719
725 void clear()
726 {
727 states_.empty();
728 states_.append(State{});
729 states_[0].link = -1;
730 states_[0].len = 0;
731 states_[0].first_pos = 0;
732 states_[0].terminal = false;
733 last_ = 0;
734 }
735
742 void extend(const char ch)
743 {
744 const auto c = static_cast<unsigned char>(ch);
745
746 const int cur = static_cast<int>(states_.size());
747 states_.append(State{});
748 states_[static_cast<size_t>(cur)].len = states_[static_cast<size_t>(last_)].len + 1;
749 states_[static_cast<size_t>(cur)].first_pos = states_[static_cast<size_t>(cur)].len - 1;
750
751 int p = last_;
752 while (p != -1 and states_[static_cast<size_t>(p)].next[c] == -1)
753 {
754 states_[static_cast<size_t>(p)].next[c] = cur;
755 p = states_[static_cast<size_t>(p)].link;
756 }
757
758 if (p == -1)
759 states_[static_cast<size_t>(cur)].link = 0;
760 else
761 {
762 if (const int q = states_[static_cast<size_t>(p)].next[c];
763 states_[static_cast<size_t>(p)].len + 1 == states_[static_cast<size_t>(q)].len)
764 states_[static_cast<size_t>(cur)].link = q;
765 else
766 {
767 const int clone = static_cast<int>(states_.size());
768 // Copy q's state before append: append may reallocate states_,
769 // invalidating any reference into the old buffer.
770 const State clone_state = states_[static_cast<size_t>(q)];
771 states_.append(clone_state);
772 states_[static_cast<size_t>(clone)].len = states_[static_cast<size_t>(p)].len + 1;
773 states_[static_cast<size_t>(clone)].terminal = false;
774 // Enforce invariant: only root (state 0) may have link == -1
775 if (states_[static_cast<size_t>(clone)].link == -1)
776 states_[static_cast<size_t>(clone)].link = 0;
777
778 while (p != -1 and states_[static_cast<size_t>(p)].next[c] == q)
779 {
780 states_[static_cast<size_t>(p)].next[c] = clone;
781 p = states_[static_cast<size_t>(p)].link;
782 }
783
784 states_[static_cast<size_t>(q)].link = clone;
785 states_[static_cast<size_t>(cur)].link = clone;
786 }
787 }
788
789 last_ = cur;
790 }
791
798 void build(const std::string_view text)
799 {
800 clear();
801 for (const char c : text)
802 extend(c);
803
805 }
806
814 [[nodiscard]] bool contains(const std::string_view pattern) const
815 {
816 int state = 0;
817 for (const unsigned char c : pattern)
818 {
819 state = states_[static_cast<size_t>(state)].next[c];
820 if (state == -1)
821 return false;
822 }
823
824 return true;
825 }
826
833 [[nodiscard]] size_t distinct_substring_count() const
834 {
835 size_t total = 0;
836 for (size_t i = 1; i < states_.size(); ++i)
837 {
838 const State &s = states_[i];
839 const State &parent = states_[static_cast<size_t>(s.link)];
840 total += s.len - parent.len;
841 }
842
843 return total;
844 }
845
854 [[nodiscard]] std::string longest_common_substring(const std::string_view other) const
855 {
856 int state = 0;
857 size_t len = 0;
858
859 size_t best_len = 0;
860 size_t best_pos = 0;
861
862 for (size_t i = 0; i < other.size(); ++i)
863 {
864 const auto c = static_cast<unsigned char>(other[i]);
865
866 while (state != 0 and states_[static_cast<size_t>(state)].next[c] == -1)
867 {
868 state = states_[static_cast<size_t>(state)].link;
869 len = states_[static_cast<size_t>(state)].len;
870 }
871
872 if (states_[static_cast<size_t>(state)].next[c] != -1)
873 {
874 state = states_[static_cast<size_t>(state)].next[c];
875 ++len;
876 }
877 else
878 {
879 state = 0;
880 len = 0;
881 }
882
883 if (len > best_len)
884 {
885 best_len = len;
886 best_pos = i;
887 }
888 }
889
890 if (best_len == 0)
891 return "";
892
893 return std::string(other.substr(best_pos + 1 - best_len, best_len));
894 }
895
902 [[nodiscard]] size_t state_count() const noexcept
903 {
904 return states_.size();
905 }
906
913 [[nodiscard]] const Array<State> &states() const noexcept
914 {
915 return states_;
916 }
917};
918
933inline std::string longest_common_substring_sam(const std::string_view a, const std::string_view b)
934{
936 sam.build(a);
937 return sam.longest_common_substring(b);
938}
939} // namespace Aleph
940
941#endif // SUFFIX_STRUCTURES_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error()
Throws std::domain_error unconditionally.
Definition ah-errors.H:702
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Naive compressed suffix tree (didactic implementation).
Naive_Suffix_Tree & operator=(Naive_Suffix_Tree &&other) noexcept
Exchange this tree with another, which is left with the previous text and nodes of this one.
Array< size_t > find_all(const std::string_view pattern) const
Return all occurrences of a pattern.
void replace_child(const size_t parent, const size_t old_child, const size_t new_child)
Naive_Suffix_Tree & operator=(const Naive_Suffix_Tree &other)=default
Copy the text and the nodes of another tree.
Naive_Suffix_Tree(Naive_Suffix_Tree &&other)
Take the text and the nodes of another tree, which is left as the tree of the empty text,...
Naive_Suffix_Tree(const std::string_view text="")
Construct a naive suffix tree.
void swap(Naive_Suffix_Tree &other) noexcept
Exchange in O(1) the text and the nodes of this tree and another.
static constexpr size_t npos
size_t node_count() const noexcept
Return the number of nodes in the tree.
size_t create_node(const size_t start, const size_t end, const size_t parent, const size_t suffix_index)
size_t find_child_by_first_char(const size_t node, const char c) const
void build(const std::string_view text)
Build or rebuild the suffix tree for text.
size_t text_size() const noexcept
Return the text size (without terminal marker).
void insert_suffix(const size_t suffix_start)
void collect_leaf_suffixes(const size_t node, Array< size_t > &out) const
bool contains(const std::string_view pattern) const
Return true if the pattern appears in the text.
static char choose_terminal(const std::string_view s)
Naive_Suffix_Tree(const Naive_Suffix_Tree &other)=default
Copy the text and the nodes of another tree.
const Array< Node > & nodes() const noexcept
Return the internal node array for inspection/debugging.
Suffix automaton (SAM) over byte alphabet.
Suffix_Automaton(Suffix_Automaton &&other)
Take the states of another automaton, which is left empty, with the root state only,...
std::string longest_common_substring(const std::string_view other) const
Find the longest common substring between the built SAM text and other.
void build(const std::string_view text)
Build the SAM from an entire string.
bool contains(const std::string_view pattern) const
Return true if pattern is a substring of the built text.
Suffix_Automaton & operator=(Suffix_Automaton &&other) noexcept
Exchange this automaton with another, which is left with the previous states of this one.
const Array< State > & states() const noexcept
Access the internal states array for testing/inspection.
Suffix_Automaton & operator=(const Suffix_Automaton &other)=default
Copy the states of another automaton.
void swap(Suffix_Automaton &other) noexcept
Exchange in O(1) the states of this automaton and another.
void mark_terminals()
Traverse suffix links from last and mark all states as terminal.
size_t distinct_substring_count() const
Count the number of distinct substrings in the built text.
Suffix_Automaton(const Suffix_Automaton &other)=default
Copy the states of another automaton.
Suffix_Automaton()
Construct an empty suffix automaton (SAM) with only the root state.
size_t state_count() const noexcept
Return the number of states in the SAM.
void clear()
Reset the automaton to its initial empty state (root only).
void extend(const char ch)
Extend the SAM with a single character.
Array< size_t > all_positions(const size_t n)
Generate an array of all positions from 0 to n.
void sort_matches(Array< size_t > &a)
Sort matches in place using introsort.
Main namespace for Aleph-w library functions.
and std::convertible_to< std::invoke_result_t< const KeyFn &, size_t >, int > void counting_sort_indices(Array< size_t > &sa, Array< size_t > &tmp, const size_t n, const int min_key, const int max_key, const KeyFn &key_of)
Stable counting sort on an index array by integer keys.
Array< size_t > lcp_array_kasai(const std::string_view text, const Array< size_t > &sa)
Compute LCP array from text and suffix array using Kasai.
std::string longest_common_substring_sam(const std::string_view a, const std::string_view b)
Convenience function: LCS via suffix automaton.
and
Check uniqueness with explicit hash + equality functors.
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
void introsort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using introsort (introspective sort).
Array< size_t > suffix_array(const std::string_view text)
Build suffix array with doubling algorithm.
size_t parent
Parent node index.
size_t start
Start index in text.
size_t end
End index in text.
Array< size_t > children
Indices of children nodes.
size_t suffix_index
Index of suffix starting at leaf.
bool terminal
true if state is terminal
std::array< int, 256 > next
Transitions for each byte.
size_t first_pos
First occurrence end position.
size_t len
Max length of substring in this state.
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Comprehensive sorting algorithms and search utilities for Aleph-w.