|
| 1 | +/** |
| 2 | + * @file |
| 3 | + * @brief Aho-Corasick Algorithm[](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick) - Multi-pattern string search. |
| 4 | + * @details Builds a trie + failure links for O(n + m + z) multi-pattern matching. Inspired by GFG/LeetCode #30. |
| 5 | + * @author [Your Name](https://github.com/yourhandle) |
| 6 | + */ |
| 7 | +#include <cassert> |
| 8 | +#include <iostream> |
| 9 | +#include <queue> |
| 10 | +#include <string> |
| 11 | +#include <unordered_map> |
| 12 | +#include <vector> |
| 13 | + |
| 14 | +namespace strings { namespace aho_corasick { |
| 15 | + // Trie node struct |
| 16 | + struct TrieNode { |
| 17 | + std::unordered_map<char, int> children; |
| 18 | + int fail = 0; |
| 19 | + std::vector<int> output; // Pattern indices ending here |
| 20 | + }; |
| 21 | + |
| 22 | + // Build trie + failure links |
| 23 | + std::vector<TrieNode> buildTrie(const std::vector<std::string>& patterns) { |
| 24 | + // ... (implement: insert patterns, BFS for fails) |
| 25 | + } |
| 26 | + |
| 27 | + // Search function |
| 28 | + std::vector<std::pair<size_t, size_t>> search(const std::string& text, const std::vector<std::string>& patterns) { |
| 29 | + // ... (implement: traverse text, collect matches via output links) |
| 30 | + return {}; // vector of (text_pos, pattern_index) |
| 31 | + } |
| 32 | +} } // namespace |
| 33 | + |
| 34 | +static void test() { |
| 35 | + std::vector<std::string> pats = {"he", "she", "his", "hers"}; |
| 36 | + std::string text = "ushers"; |
| 37 | + auto matches = strings::aho_corasick::search(text, pats); |
| 38 | + assert(matches.size() == 3); // Expected: (0,"ushe"), etc. — adjust asserts |
| 39 | + // More tests: empty, no-match, overlaps. |
| 40 | + std::cout << "All tests passed!\n"; |
| 41 | +} |
| 42 | + |
| 43 | +int main() { test(); return 0; } |
0 commit comments