首页 > 代码库 > KMP - 简单应用
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;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。