#include <stdio.h> #include <string.h> #include <stdlib.h> int string1[1000000],string2[1000000]; int next[1000000]; void get_next(int len) { int i=0,j=-1; next[0] = -1; while(i<len) { if(j==-1 || string2[i]==string2[j]) { i++; j++; next[i] = j; } else { j = next[j]; } } } int Index_KMP(int x,int y,int pos) { int i=pos,j=0;get_next(y); while(i<x && j<y) { if(j==-1 || string1[i]==string2[j]) //j=-1 { i++; j++; } else { j = next[j]; } } if(j==y) { return i-j+1; } else { return -1; } } int main() { int n,i,m,x; while(scanf("%d",&n)!=EOF){ for(i=0;i<n;i++){scanf("%d",&string1[i]);}scanf("%d",&m);for(i=0;i<m;i++){scanf("%d",&string2[i]);}x = Index_KMP(n,m,0);//找到模式串的在主串中的位置if(x!=-1){//此题要唯一确定一对l,r值;理解为确定唯一的子串,即模式串在主串中只出现一次,然后输出匹配模式串在主串中的首位置和末位置int t = Index_KMP(n,m,x+m-1);if(t!=-1){printf("-1\n");}else{printf("%d %d\n",x,x+m-1);}}else{printf("-1\n");} } return 0; }
转载于:https://www.cnblogs.com/CCCrunner/p/6444627.html
相关资源:JAVA上百实例源码以及开源项目