AC代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n, m;
char a[1000005];
char b[10005];
int p[10005];
void Pre(){
int i, j;
j = -1;
p[0] = -1;
for( i = 1; i < m; i++ ){
while( j >= 0 && b[j+1] != b[i] ){
j = p[j];
}
if( b[j+1] == b[i] ){
j++;
}
p[i] = j;
}
}
int solve(){
int i, j, cnt;
cnt = 0;
j = -1;
for( i = 0; i < n; i++ ){
while( j >= 0 && b[j+1] != a[i] ){
j = p[j];
}
if( b[j+1] == a[i] ){
j++;
}
if( j == m - 1 ){
cnt++;
}
}
return cnt;
}
int main(){
int i, j, T;
cin >> T;
while( T-- ){
scanf( "%s%s", b, a );
n = strlen( a );
m = strlen( b );
Pre();
printf( "%d\n", solve() );
}
return 0;
}
这时之前学数据结构是的模版。。。。以后忘记了看。。。。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//该算法能够在m+n的时间复杂度内求出B字符串在A中的首位置
//详细解释见 严蔚敏版 数据结构 第四章串操作 80页
int main()
{
int searchnext( char b[], int next[] );
char a[100], b[100];
int next[100];
int i, j, lengtha, lengthb;
scanf( "%s%s", a, b );
searchnext( b, next );
lengtha = strlen(a);
lengthb = strlen(b);
for( i = 0, j = 0; i < lengtha && j < lengthb; ) //将lengtha 与 lengthb 改成 strlen(a) strlen(b)就不行了
{
if( j == -1 || a[i] == b[j])
{
i ++;
j ++;
}
else
j = next[j];
}
if( j < strlen(b) )
{
printf(" connot find answer!");
}
else
printf( "%d", i-strlen(b)+1);
return 0;
}
int searchnext( char b[], int next[] ) //***************求next数组
{
int i, j;
next[0] = -1;
for( i = 0, j = -1; i <= strlen(b); )
{
if( j == -1 || b[i] == b[j])
{
i ++;
j ++;
if( b[i] != b[j] )
next[i] = j;
else
next[i] = next[j];
}
else
j = next[j];
}
return 1;
}