The topic describes whether string2 is a substring of string1 given two strings string1 and string2. Input input contains multiple sets of data, each set of test data contains two lines, the first row represents string1 (length less than 1000000), the second line represents string2 (length less than 1000000), string1 and string2 ensure that no spaces appear. Output for each set of input data, if string2 is a string1 substring, the output string2 in string1 position, if not, output-1. Sample input
Abca12345645abcddd
Sample output
14-1
This is also a simple KMP algorithm, and learn the password must be the same as the program, but there is a word in this topic is to ensure that two strings do not appear space, so the input string should be used scanf ("%s", S1);
And can not use gets (S1), if use gets the words will always WA;
#include <stdio.h> #include <string.h> #define N 1000001char s1[n],s2[n];int next[n];void getnext () { int i=0,j=-1; Next[0]=-1; while (s2[i]!= ') { if (J==-1 | | s2[i]==s2[j]) { i++; j + +; next[i]=j; } else j=next[j];} } void KMP () { int i=0,j=0; GetNext (); int Len1=strlen (s1); int Len2=strlen (s2); while (I<len1 && j<len2) { if (J==-1 | | s1[i]==s2[j]) { i++; j + +; } else j=next[j]; } if (j>=len2) { printf ("%d\n", i-len2+1); } else { printf (" -1\n");} } int main () {while (~scanf ("%s", S1)) { scanf ("%s", S2); KMP (); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
KMP Simple Application