Boyer–Moore–Horspool algorithm

122 阅读1分钟

Horspool algorithm

输入 two lines and only characters “ACGT” in the string. the first line
is string (< = 102000) the second line is text(< = 700000)

输出 position of the string in text else -1

样例输入

GGCCTCATATCTCTCT
CCCATTGGCCTCATATCTCTCTCCCTCCCTCCCCTGCCCAGGCTGCTTGGCATGG

样例输出

6

思路:动态规划题目。按照Horspool算法来做,我们先根据输入模式构造一个表,表里面包含模式字符以及对应字符应该移动的位数。
移动位数由字母出现次数来计算。
然后我们从右往左比较,如果遇到不匹配的字符,这时我们构造好的表格就起到了作用,将模式依次往右移动次数,再接着进行比较,知道匹配成功或者匹配结尾字符失败,返回-1。

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
char str[20000],text[20000];
int Horspool_Match(char *str,char *text)
{
	int str_len=strlen(str);
	int text_len=strlen(text);
	int match[27]={
		0
	};
	for(int i=0;i<str_len;i++)
	{
		match[str[i]-'A']=str_len-i+1;//根据模式构造字母移动次数表
	}
	int p=str_len-1;
	while(p<text_len)
	{
		int k=0;//记录每次匹配成功移动的次数
		while(str[str_len-1-k]==text[p-k])//如果匹配则将模式依次向右移动
		{
			k++;
		}
		if(k==str_len){//匹配结束,输出模式与文本匹配的位置编号(+1)
			return p-str_len+1;
		}
		else{
			p+=match[text[p]-'A'];//不匹配,模式向右移动(根据表格中的数值进行移动)
		}
	}
	return -1;//匹配失败,返回-1
} 
int main()
{
	cin>>str>>text;
	cout<<Horspool_Match(str,text)<<endl;
	return 0;
}