字符串hash kmp算法

#include <stdio.h>


unsigned int BKDRHash(char* str){//字符串hash
	unsigned int seed = 131;// 31 131 1313 13131 131313 etc..
	unsigned int hash = 0;
	while (*str){
		hash = hash * seed + (*str++);
	}
	return hash&0x7fffffff;
}

int main(){
	unsigned int res = BKDRHash("abcdef");
	printf("%d\n",res);
	return 0;
}
#include<stdio.h>
#include<string.h>

#define P 6

unsigned int hasha(char *url,int mod);
unsigned int hashb(char *url,int mod);
int kmp(char *str, char *pat);


int fail[P];

int main(){
	int n1 = hasha("abcde",25013);
	int n2 = hashb("abcde",25013);
	int n3 = hasha("abcde",25013);
	printf("%d\t%d\t%d\t\n",n1,n2,n3);
	unsigned int n4=0xffff;
	printf("%d\n",n4);
	char *str1 = "Borland International";
	char *str2 = "nation";
	char *ptr;
	ptr = strstr(str1,str2);//字串查找函数string.h
	printf("The substring is:%s\n",ptr);
	int n=kmp("abcabcabmdefghijklmnopq","abcabm");
	printf("%d\n",n);
	return 0;
}


unsigned int hasha(char* url,int mod){//mod选择足够大的质数
	unsigned int n = 0;//一个int占4字节个
	char *b = (char*)&n;
	for(int i=0; url[i];++i)
		b[i%4] ^=url[i];//^异或
	return n%mod;
}

unsigned int hashb(char* url,int mod){
	unsigned int h = 0;
	unsigned int g;
	while(*url){
		h = (h<<4) + *url++;
		g = h & 0xf0000000;
		if(g)
			h ^=g>>24;
		h &=~g;
	}
	return h%mod;
}

int kmp(char *str,char *pat){
	int i,j,k;
	memset(fail,-1,sizeof(fail));
	for(i=1;pat[i];++i){
		for(k=fail[i-1];k>=0&&pat[i]!=pat[k+1];k=fail[k]); //abaaabaaabc -1-100012345-1计算c时
		if(pat[k+1]==pat[i]) fail[i]=k+1;
	}
	i=j=0;
	while(str[i]&&pat[j]){
		if(str[i]==pat[j]) ++i,++j;
		else if(j==0) ++i;
		else j=fail[j-1]+1;
	}
		if(pat[j]) return  -1;
		else return i-j;
}

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/bazingaz/article/details/6863810
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞