From dee98098429149764b0f3d499f69062b13371164 Mon Sep 17 00:00:00 2001 From: Kotecha Udit Hitendra <64374551+kirito-udit@users.noreply.github.com> Date: Sat, 2 Oct 2021 20:09:49 +0530 Subject: [PATCH] Create Aho-Corasick Algorithm.cpp --- Algorithms/Aho-Corasick Algorithm.cpp | 53 +++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Algorithms/Aho-Corasick Algorithm.cpp diff --git a/Algorithms/Aho-Corasick Algorithm.cpp b/Algorithms/Aho-Corasick Algorithm.cpp new file mode 100644 index 0000000..b9bee51 --- /dev/null +++ b/Algorithms/Aho-Corasick Algorithm.cpp @@ -0,0 +1,53 @@ +const int K = 26; + +struct Vertex { + int next[K]; + bool leaf = false; + int p = -1; + char pch; + int link = -1; + int go[K]; + + Vertex(int p=-1, char ch='$') : p(p), pch(ch) { + fill(begin(next), end(next), -1); + fill(begin(go), end(go), -1); + } +}; + +vector t(1); + +void add_string(string const& s) { + int v = 0; + for (char ch : s) { + int c = ch - 'a'; + if (t[v].next[c] == -1) { + t[v].next[c] = t.size(); + t.emplace_back(v, ch); + } + v = t[v].next[c]; + } + t[v].leaf = true; +} + +int go(int v, char ch); + +int get_link(int v) { + if (t[v].link == -1) { + if (v == 0 || t[v].p == 0) + t[v].link = 0; + else + t[v].link = go(get_link(t[v].p), t[v].pch); + } + return t[v].link; +} + +int go(int v, char ch) { + int c = ch - 'a'; + if (t[v].go[c] == -1) { + if (t[v].next[c] != -1) + t[v].go[c] = t[v].next[c]; + else + t[v].go[c] = v == 0 ? 0 : go(get_link(v), ch); + } + return t[v].go[c]; +}