KMP

Description
给你两个字符串,求第二个串(模式串)在第一个串(母串)中的位置。

Input
两行,两个长度∈[1,1000000]的只含有大小写字母的字符串。

Output
如果能够匹配,输出模式串第一个字母在母串的位置。否则输出0。

Sample Input1
10 2
abaabababa
ba

Sample Output1
2

Sample Input2
10 2
abaabababa
bb

Sample Output2
0


Hint
热烈欢迎Hash的,强烈鄙视输0骗分的。

kmp??!!

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int i , j , next[1000003];
 8 char a[1000003] , b[1000003] ;
 9 
10 
11 int main() {
12 //    freopen( "10722.in","r",stdin ) ;
13 //    freopen( "10722.out","w",stdout ) ;
14 scanf( "%d%d" ,&i , &j ) ;
15 scanf( "%s%s" ,b , a ) ;
16 
17 for( int q = 1 , k = 0 ; q <= j ; ++ q ) {
18 while( k > 0 && a[q] != a[k] )
19 k = next[k-1] ;
20 if( a[q] == a[k] ) ++k ;
21 next[q] = k ;
22 }
23 
24 for ( int x = 0,q = 0; x < i; ++x) {
25 while(q > 0 && b[x] != a[q])
26 q = next[q-1];
27 if ( b[x] == a[q])    q++;
28 if (q == j)
29 {
30 printf("%d
",( x-j+2 ) );
31 return 0 ;
32 }
33 }
34 printf( "0
" ) ;
35 return 0;
36 }
原文地址:https://www.cnblogs.com/Ateisti/p/5879087.html