abcde a3 aaaaaa aa #
0 3
/*********************************************************** > OS : Linux 3.13.0-24-generic (Mint-17) > Author : yaolong > Mail : dengyaolong@yeah.net > Time : 2014年09月24日 星期三 15时31分51秒 **********************************************************/ #include <iostream> #include <cstdio> #include <string> #include <cstring> using namespace std; int next[12345]; char p[12345]; char T[1234567]; void build_next ( int m ) { next[1] = 0; int k = 0; for ( int q = 2; q <= m; q++ ) { while ( k > 0 && p[k + 1] != p[q] ) { k = next[k]; } if ( p[k + 1] == p[q] ) { k = k + 1; } next[q] = k; } } int kmp ( int n, int m ) { build_next ( m ); int q = 0; int res = 0; for ( int i = 1; i <= n; i++ ) { while ( q > 0 && p[q + 1] != T[i] ) { q = next[q]; } if ( p[q + 1] == T[i] ) { q = q + 1; } if ( q == m ) { //cout << "Here" << i-m<<"q"; ++res; //q = next[q]; q=i+1; //cout<<q<<endl; } } return res; } int main() { int C; p[0] = T[0] = '1'; while ( scanf ( "%s", T + 1 ) != EOF ) { if ( T[1] == '#' ) { break; } scanf ( "%s", p + 1 ); printf ( "%d\n", kmp ( strlen ( T ) - 1, strlen ( p ) - 1 ) ); } return 0; }
原文地址:http://blog.csdn.net/dengyaolongacmblog/article/details/39546309