思想是将字符串转化为整数进行比较,采用取余数的hash函数进行转换,假设目标字符串长度为m,源字符串长度为n,(m<n),预处理阶段需要O(m)的时间,匹配时间是O((n-m+1)m),预计运行时间为O(n+m)。
首先将原串中前m个字符,和目标串的值进行比较,若不形同,则向前移动一位,再次比较,相同时需采用朴素算法讲两个字符串逐位比较。下面是c++实现。
#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;
int strstr(string sor, string tar) {
int n = sor.length();
int m = tar.length();
int pow = 1,base=31;
for (int i = 0; i < m; i++)
{
pow =( pow * 31) % base;
}
int tarhash = 0;
for (int i = 0; i < m; i++)
{
tarhash = (tarhash * 31 + tar[i])% base;
}
int sorhash = 0;
for (int i = 0; i < n; i++)
{
sorhash = (sorhash * 31 + sor[i]) % base;
if (i < m - 1)
continue;
if (i >= m)
{
sorhash = sorhash - (sor[i - m] * pow) % base;
if (sorhash < 0)
sorhash += base;
}
if (tarhash == sorhash)
{
if (sor.substr(i - m + 1, m) == tar) {
return i - m + 1;
}
}
}
}
void main() {
string a, b;
cin >> a >> b;
cout<<strstr(a, b);
system("pause");
}
本文介绍了一种高效的字符串匹配算法——Rabin-Karp算法,该算法通过将字符串转化为整数并使用取余数的hash函数进行转换,实现了在O(n+m)的时间复杂度内完成匹配。文章详细解释了算法思想,并提供了C++实现代码。
191

被折叠的 条评论
为什么被折叠?



