diff --git a/strings/aho_corasick.cpp b/strings/aho_corasick.cpp new file mode 100644 index 00000000000..bbe8355c21a --- /dev/null +++ b/strings/aho_corasick.cpp @@ -0,0 +1,43 @@ +/** + * @file + * @brief Aho-Corasick Algorithm[](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick) - Multi-pattern string search. + * @details Builds a trie + failure links for O(n + m + z) multi-pattern matching. Inspired by GFG/LeetCode #30. + * @author [Saurabh Kokate](https://github.com/kokatesaurabh) + */ +#include +#include +#include +#include +#include +#include + +namespace strings { namespace aho_corasick { + // Trie node struct + struct TrieNode { + std::unordered_map children; + int fail = 0; + std::vector output; // Pattern indices ending here + }; + + // Build trie + failure links + std::vector buildTrie(const std::vector& patterns) { + // ... (implement: insert patterns, BFS for fails) + } + + // Search function + std::vector> search(const std::string& text, const std::vector& patterns) { + // ... (implement: traverse text, collect matches via output links) + return {}; // vector of (text_pos, pattern_index) + } +} } // namespace + +static void test() { + std::vector pats = {"he", "she", "his", "hers"}; + std::string text = "ushers"; + auto matches = strings::aho_corasick::search(text, pats); + assert(matches.size() == 3); // Expected: (0,"ushe"), etc. — adjust asserts + // More tests: empty, no-match, overlaps. + std::cout << "All tests passed!\n"; +} + +int main() { test(); return 0; }