Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create aho_corasick.cpp #3027

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
kokatesaurabh wants to merge 2 commits into TheAlgorithms:master
base: master
Choose a base branch
Loading
from kokatesaurabh:master
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions strings/aho_corasick.cpp
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -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 <cassert>
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
#include <vector>

namespace strings { namespace aho_corasick {
// Trie node struct
struct TrieNode {
std::unordered_map<char, int> children;
int fail = 0;
std::vector<int> output; // Pattern indices ending here
};

// Build trie + failure links
std::vector<TrieNode> buildTrie(const std::vector<std::string>& patterns) {
// ... (implement: insert patterns, BFS for fails)
}

// Search function
std::vector<std::pair<size_t, size_t>> search(const std::string& text, const std::vector<std::string>& patterns) {
// ... (implement: traverse text, collect matches via output links)
return {}; // vector of (text_pos, pattern_index)
}
} } // namespace

static void test() {
std::vector<std::string> 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; }

AltStyle によって変換されたページ (->オリジナル) /