Rabin-karp字符串匹配算法

本文介绍了一种高效的字符串匹配算法——Rabin-Karp算法,该算法通过将字符串转化为整数并使用取余数的hash函数进行转换,实现了在O(n+m)的时间复杂度内完成匹配。文章详细解释了算法思想,并提供了C++实现代码。

思想是将字符串转化为整数进行比较,采用取余数的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");
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值