From b0ac5ece81d137fbdf1fe9fad1ada72671980444 Mon Sep 17 00:00:00 2001 From: keiyanishio Date: Tue, 8 Nov 2022 11:40:13 -0300 Subject: [PATCH] Adding Rabin Karp Algorithm in C --- c/String Algorithms/rabin_karp.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 c/String Algorithms/rabin_karp.c diff --git a/c/String Algorithms/rabin_karp.c b/c/String Algorithms/rabin_karp.c new file mode 100644 index 000000000..2fb5334ef --- /dev/null +++ b/c/String Algorithms/rabin_karp.c @@ -0,0 +1,26 @@ +int rabin_karp(char* txt, char* pat){ + int n = strlen(txt); + int m = strlen(pat); + int pat_hash = 0; + int txt_hash = 0; + + for (int k = 0; k < m ; k++){ + pat_hash += pat[k]; + txt_hash += txt[k]; + } + + for (int i = 0; i <= n - m; i++) { + if(pat_hash == txt_hash){ + for(int j = 0; j < m; j++){ + if(pat[j] != txt[i+j]){ + break; + } + } + if(j == m){ + return i; + } + } + txt_hash = txt_hash - txt[i] + txt[i+m]; + } + return -1; +} \ No newline at end of file