[SDUT](2772)数据结构实验之串一:KMP简单应用 ---KMP(串)
数据结构实验之串一:KMP简单应用
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Example Input
abc a 123456 45 abc ddd
Example Output
1 4 -1
解题新知:
AC代码:
#include<iostream> #include<cstring> #include<cstdio> using namespace std; int next[1000005]; void setNext(char *p) { int t=next[0]=-1; int plen=strlen(p); int j=0; while(j<plen-1) { if(t<0||p[j]==p[t]) { j++; t++; //next[j]=p[j]!=p[t]?t:next[t]; next[j]=t; } else t=next[t]; } } int kmp(char *t,char *p) { setNext(p); int i=0; int j=0; int m=strlen(t); int n=strlen(p); while(i<m && j<n) { if(j<0||t[i]==p[j]) { i++; j++; } else j=next[j]; } if(j==n) return i-j+1; else return -1; } int main() { char p[1000005]; char t[1000005]; while(scanf("%s %s",t,p)!=EOF) { int r=kmp(t,p); printf("%d\n",r); } return 0; }