The algorithm notes hoorspool algorithm

The algorithm notes hoorspool algorithm

From right to left character scanning, if all matches succeed, then find a matching string, if they do not match the time, you need to model the right move, this time to consider the text mode with the last character of the text alignment character C

  1. When the character is not in mode
    ... C ...
    BARBER rightward m-bit mode

    When the surface of the m-1 current character does not contain the last character, moving bits m

  2. When the character mode

    M-1 both in front of characters has a character matching and c
    ... C ... (c appears multiple times in mode)
    CACBAB movement patterns align the character before m-1 rightmost character in the character and text


    1. t © = -. mode from the rightmost character string c and the right end of the pattern string otherwise
      - the pattern string length m, (m-1 th free before c)

    Moving table recorded in the pattern corresponding to the text character alignment, we need to move a number of elements, BAOBAB moving table below:
    Here Insert Picture Description
    Here Insert Picture Description
    Here Insert Picture DescriptionCode as follows:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 1000
int hoorspool(char *t,char *p)
{
	int n=strlen(t);
	int m=strlen(p);
	int table[MAX];//将表中所有原数置为模式长度m
	for(int i=0;i<MAX;i++){ 
	    table[i]=m;
	}
	for(int i=0;i<m;i++){//模式中的字符设另为与模式最右端的距离
	    table[p[i]]=m-1-i;
	}
	int i=m-1;
	while(i<=n-1){ //进行匹配
		int k=0;
		while(k<m&&(p[m-1-k]==t[i-k])){
			k++;
		}
		if(k==m)
		    return i-m+1;
		else
		    i=i+table[t[i]];
	}
	return -1;
}
int main()
{
	 char t[MAX],p[MAX];
	 scanf("%s%s",t,p);
	 int x=hoorspool(t,p);
	 if(x==-1)
	     printf("Not find!");
	 else
	     printf("location:%d",x);
     return 0;
} 
Published 11 original articles · won praise 1 · views 1282

Guess you like

Origin blog.csdn.net/superman_lile/article/details/105393353