Horspool算法C語言實現

#include<stdio.h>
#include <iostream> 
#include <string.h>
 
int table[256];
int skip( char *p,int m){
	for(int i=0;i<256;i++)
		table[i]=m;//initialize the all the value of table firstly
	for(int j=0;j<m-1;j++){
		table[p[j]]=m-1-j;// from left scan the pattern
	}
	return *table;//return the value of table
}
int horspool(char *p,char *t,int m,int n){
	skip(p,m);//call function skip
	int i=m-1;
	
	while(i<=n-1){
		int k=0;//at first the number of match is zero
		while(k<m&&p[m-1-k]==t[i-k]){//match the pattern by  character ;zhuzi zhuzi de pipei
			k++;
		}
		if(k==m)
			return i-m+1;//match successly,return the number
		else
			i=table[t[i]]+i;//fail,go on skipping
	}
			return -1;//finally fail return -1
}

int main(){
	char p[256];
	char t[256];
	scanf("%s%s",&p,&t);
	int m=strlen(p);
	int n=strlen(t);
	int x=horspool(p,t, m,n);
	printf("%d",x);
	
	
}
  1. 創建移動表.

  2. 首先初始化所有的字符跳轉距離爲模式文本pattern的長度,其次再從數組下標0號開始計算它到字符串的串尾元素的距離。

  3. 串尾元素不參與計算,默認爲字符串長度,如果在非串尾的位置出現了和串尾元素相等的元素則用那個計算出來的跳轉值覆蓋掉默認的串尾元素的跳轉值。

  4. 執行horspool函數,進行匹配。首先初始化k=0表示匹配的字符個數爲0,給一個循環:在滿足k<pattern的長度時,後面一個個的進行匹配。跳出循環時,當k=pattern的長度時,代表已經匹配成功;如果不等於k不等於長度 說明沒有匹配到,那我們就移動表,移動的值通過先前創建的移動表來讀取。

  5. 如果跳出大循環,說明在整個文本中都不能匹配pattern,則輸出-1.結束程序。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章