KMP - 简单应用
#include<stdio.h> #include<string.h> char s1[1000005],s2[1000005]; int next[1000005]; void get_next(char s[1000005]) { int i = 0; int len = strlen(s); next[0] = -1; int j = -1; while(i < len-1) { if( j == -1 || s[i] == s[j]) { ++i; ++j; if( s[i] != s[j]) next[i] = j; else next[i] = next[j]; } else j = next[j]; } } int kmp(char *s,char *p) { int len1 = strlen(s); int len2 = strlen(p); int i = 0; int j = 0; while( i < len1 && j < len2) { if( j == -1 || s[i] == p[j]) { ++i; ++j; } else j = next[j]; } if( j >= len2) return i-len2+1; else return -1; } int main() { while(scanf("%s",s1)!=EOF) { scanf("%s",s2); get_next(s2); int wz = kmp(s1,s2); printf("%d\n",wz); } return 0; }
2.
#include <stdio.h> #include <string.h> char s[1000001],p[1000001]; int next[1000001]; void getnext(char *p,int *next) { int j,k; next[0] = -1; j = 0; k = -1; while(j<strlen(p) - 1) { if(k == -1 || p[j] == p[k]) // 匹配情况下,p[j] == p[k] { j++; k++; next[j] = k; } // p[j] !=p[k]; else k = next[k]; } } int KMPmatch(char *s,char *p) { int i,j; i = 0; j = 0; getnext(p,next); while(i<strlen(s)) { if(j == -1 || s[i] == p[j]) { i++; j++; } else j = next[j]; if(j == strlen(p)) return i - strlen(p)+1; } return -1; } int main() { while(scanf("%s%s",s,p)!=EOF) { printf("%d\n",KMPmatch(s,p)); } return 0; }