diff --git a/README.md b/README.md index a1eef1a..c6f5c67 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,9 @@ This Repo is For those who want to contribute in an open Source Repo for Hacktob | |── vector.cp │   ├── sets-subarray-partition-O(n).cpp │   └── stack.cpp +├── Strings +│   ├── Rabin-Karp-Algorithm.cpp +│   ├── Z-Function.cpp ├── Dynamic Programming │   ├── basic-fabonic.cpp │   ├── binomial-coefficients.cpp diff --git a/Strings/Rabin-Karp-Algorithm.cpp b/Strings/Rabin-Karp-Algorithm.cpp new file mode 100644 index 0000000..3a024da --- /dev/null +++ b/Strings/Rabin-Karp-Algorithm.cpp @@ -0,0 +1,72 @@ +/* + Rabin-Karp Algorithm: + source : https://cp-algorithms.com/string/rabin-karp.html +*/ + +#include +using namespace std; +#define int long long + +const int BASE = 31, MOD = 1e9 + 7, N = 1e6 + 5; + +vector pp(N); + +void pre() +{ + pp[0] = 1; + for (int i = 1; i < N; i++) + pp[i] = pp[i - 1] * BASE % MOD; +} + +vector rabin_karp(const string &text, const string &pat) +{ + int tn = text.size(), pn = pat.size(); + vector pref(tn + 1, 0); + for (int i = 0; i < tn; i++) + pref[i + 1] = (pref[i] + (text[i] - 'a' + 1) * pp[i]) % MOD; + int hs = 0; + for (int i = 0; i < pn; i++) + hs = (hs + (pat[i] - 'a' + 1) * pp[i]) % MOD; + + vector res; + + //checking all substrings of length pattern string + for (int i = 0; i + pn - 1 < tn; i++) + { + int curr = (pref[i + pn] - pref[i] + MOD) % MOD; + if (curr == hs * pp[i] % MOD) + res.push_back(i); + } + return res; +} + +signed main() +{ + ios::sync_with_stdio(0); + cin.tie(0); + cout.tie(0); + + pre(); + + int T = 1; + cin >> T; + while (T--) + { + string text, pat; + cin >> text >> pat; + + auto res = rabin_karp(text, pat); + if (res.size() == 0) + cout << "Not Found\n"; + else + { + cout << res.size() << '\n'; + for (auto &&x : res) + cout << ++x << ' '; + cout << '\n'; + } + cout << '\n'; + } + + return 0; +} diff --git a/Strings/Z-Function.cpp b/Strings/Z-Function.cpp new file mode 100644 index 0000000..4e09ea0 --- /dev/null +++ b/Strings/Z-Function.cpp @@ -0,0 +1,32 @@ +//Source: https://cp-algorithms.com/string/z-function.html + +//basically z[i] = k, means first k characters of string concide with k characters starting from s[i]; + +/* +Example :- +"abacaba" - [0, 0, 1, 0, 3, 0, 1] +here z[4] = 3; //0 based indexing +means first 3 characters from s[4] = first 3 character from s[0]; +*/ + +vector z_function(string &s) +{ + int n = s.size(); + vector z(n); + for (int i = 1, l = 0, r = 0; i < n; i++) + { + if (i <= r) + z[i] = min(r - i + 1, z[i - l]); + while (i + z[i] < n && s[z[i]] == s[i + z[i]]) + z[i]++; + if (i + z[i] - 1 > r) + l = i, r = i + z[i] - 1; + } + return z; +} + +/* +Example +Problem : https://codeforces.com/contest/432/problem/D +solution : https://codeforces.com/contest/432/submission/75147854 +*/