模式查找算法的 Rabin-Karp 算法的 C 程序
C 的模式匹配 − 我们必须查找一个字符串是否出现在另一个字符串中,例如,字符串“算法”存在于字符串“樸素算法”中。如果找到了,那么就会显示它的位置(即它出现的位置)。我们倾向于创建一个接收 2 个字符数组并返回位置的函数,如果没有找到匹配项则返回 -1。
Input: txt = "HERE IS A NICE CAP" pattern = "NICE" Output: Pattern found at index 10 Input: txt = "XYZXACAADXYZXYZX" pattern = "XYZX" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12
Rabin-Karp 是另一种模式搜索算法。它是 Rabin 和 Karp 提出的字符串匹配算法,用于以更有效的方式查找模式。与樸素算法一样,它也通过逐个移动窗口来检查模式,但它不会对所有情况检查所有字符,而是查找哈希值。当匹配到哈希值时,它只会继续检查每个字符。这样,每个文本子序列只有一个比较操作,这使得它成为一种更有效的模式搜索算法。
预处理时间- O(m)
Rabin-Karp 算法的时间复杂度为O(m+n),但对于最坏情况,为O(mn)。
算法
rabinkarp_algo(文本、模式、质数)
输入 − 主文本和模式。另一个质数用于查找哈希位置
输出 − 模式被找到的位置
Start pat_len := pattern Length str_len := string Length patHash := 0 and strHash := 0, h := 1 maxChar := total number of characters in character set for index i of all character in the pattern, do h := (h*maxChar) mod prime for all character index i of pattern, do patHash := (maxChar*patHash + pattern[i]) mod prime strHash := (maxChar*strHash + text[i]) mod prime for i := 0 to (str_len - pat_len), do if patHash = strHash, then for charIndex := 0 to pat_len -1, do if text[i+charIndex] ≠ pattern[charIndex], then break if charIndex = pat_len, then print the location i as pattern found at i position. if i < (str_len - pat_len), then strHash := (maxChar*(strHash – text[i]*h)+text[i+patLen]) mod prime, then if strHash < 0, then strHash := strHash + prime End
示例
#include<stdio.h>
#include<string.h>
int main (){
char txt[80], pat[80];
int q;
printf ("Enter the container string
");
scanf ("%s", &txt);
printf ("Enter the pattern to be searched
");
scanf ("%s", &pat);
int d = 256;
printf ("Enter a prime number
");
scanf ("%d", &q);
int M = strlen (pat);
int N = strlen (txt);
int i, j;
int p = 0;
int t = 0;
int h = 1;
for (i = 0; i < M - 1; i++)
h = (h * d) % q;
for (i = 0; i < M; i++){
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}
for (i = 0; i <= N - M; i++){
if (p == t){
for (j = 0; j < M; j++){
if (txt[i + j] != pat[j])
break;
}
if (j == M)
printf ("Pattern found at index %d
", i);
}
if (i < N - M){
t = (d * (t - txt[i] * h) + txt[i + M]) % q;
if (t < 0)
t = (t + q);
}
}
return 0;
}输出
Enter the container string tutorialspointisthebestprogrammingwebsite Enter the pattern to be searched p Enter a prime number 3 Pattern found at index 8 Pattern found at index 21
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP