`

Boyer-Moore

阅读更多
#include<stdio.h>
#include<string.h>
//unsigned short jump(char c);
int search(char*, char*);
int char_index(char,char*);
int main(void)
{
	//char* pattern = "norn";
	//char* pattern = "grow";
	//char* pattern = "corn";
	char* pattern = "door to door";
	//char* target = "okas from acornorn grow";
	char* target = "he went door to door";
	printf("%s\n",search(pattern,target)?"find":"not find");
	return 0;
}

int char_index(char c, char* pattern)
{
	char* tmp = pattern;
	while(*tmp){
		if(*tmp == c){
			return tmp-pattern+1;
		}
		tmp++;
	}
	return 0; 
}

/**
 * Boyer-Moore fast string searching algorithm
 */
int search(char* pattern, char* target)
{
	int len = strlen(pattern);
	//int jump = 0;
							  // 如果cur指向的字符不等于pattern的最后一个字符,则cur右移pattern的长度个字符
	while(*cur){              // 如果cur指向的字符等于pattern的最后一个字符,那么依次比较cur-1和pattern的倒数第二个字符,
							  // 如果仍然相同,依次类推,如果pattern中的字符全部被匹配,那么匹配成功
		if(*cur != pattern[len-1]){    // 如果迭代过程中出现字符不匹配的情况,那cur指针么依据被查找串中不匹配的字符在pattern中的位置移动
			cur += (len-char_index(*cur, pattern));  //    如果被查找串中不匹配的字符不在pattern中,那么cur移动pattern的长度个位置
		}else{	// 如果被查找串中不匹配的字符在pattern中,那么cur先指向该字符,然后移动的距离 = 该字符在pattern中的位置到pattern末尾的距离
			int i = 1;
			printf("\n%c",*cur);
			while(1){
				//字符在pattern中的位置到pattern末尾的距离 == 被查找串移动的距离
				if(*(cur-i) == pattern[len-1-i]){
					printf("%c",*(cur-i));
					
					if(i++ == len-1){
						printf("\n");
						printf("from position %d\n", cur-target-(len-1));
						return 1;
					}
				}else{
					cur -= i;
					break;
				}
			}
		}			
	}
	return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics