void KmpMatcher(char* t,char* p) { int* w; int lent; int lenp; int i,q; lent=strlen(t); lenp=strlen(p); w=ComputePrefix(p); q=0; for(i=0;i<lent;i++) { while(q>0&&p[q]!=t[i]) { q=w[q-1]; } if(p[q]==t[i]) { q++; } if(q==lenp) { printf("find string whith shift %d\n",i-lenp+1); q=w[q-1]; } } }
int KMP(const char* text, const char* pattern) { int text_len = strlen(text); int pattern_len = strlen(pattern); if(pattern_len == 0)// "","" { return 0; } if(text_len < pattern_len)//"", "a" { return -1; } int *prefix_value = new int[pattern_len+1]();//记得初始化! ComputePrefix(pattern, prefix_value); int last_prefix_value = 0; for(int i = 0; i < text_len; i++) { int text_index = i+last_prefix_value; int j = last_prefix_value;//已知匹配的位不用再次匹配! for(; j < pattern_len; j++) { if(text_index < text_len && text[text_index] == pattern[j]) { text_index++; } else { break; } } if(j == pattern_len) { delete[] prefix_value; return i; } else if(j > 0) { i += j-prefix_value[j]-1;//注意在此移动的位数要先减1,因为后面还有i++; last_prefix_value = prefix_value[j];//记录最大公共长度,方便以后计算比较位! } } delete[] prefix_value; return -1; }