KMP算法介绍
KMP算法要解决的问题就是在字符串(也叫主串)中的模式(pattern)定位问题。说简单点就是我们平时常说的关键字搜索。模式串就是关键字(接下来称它为P),如果它在一个主串(接下来称为T)中出现,就返回它的具体位置,否则返回-1(常用手段)。
详解算法可以参考,写的非常详细:
http://www.cnblogs.com/yjiyjige/p/3263858.html
题意:
求一个模式串在主串中出现的次数
题解:
很容易想到这题要用KMP算法求解,匹配成功一次就给ans+1,函数返回参数,输出答案即可。
代码:
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std ;
#define MAX 1000005
int next[MAX] ;
char word[MAX] , temp[MAX] ;
void kmp_pre(char x[] , int m ,int next[])
{
int i , j ;
j = next[0] = -1 ;
i = 0 ;
while(i < m)
{
while(-1 != j && x[i] != x[j]) j = next[j] ;
if(x[++i] == x[++j]) next[i] = next[j] ;
else next[i] = j ;
}
}
int KMP_Count(char x[] , int m ,char y[] , int n)
{
int i , j ;
int ans = 0 ;
kmp_pre(x , m , next) ;
i = j = 0 ;
while(i < n)
{
while(-1 != j && y[i] != x[j]) j = next[j] ;
i ++ ; j ++ ;
if(j >= m)
{
ans ++ ;
j = next[j] ;
}
}
return ans ;
}
int main()
{
int T ;
scanf("%d" , &T) ;
getchar() ;
while(T --)
{
scanf("%s" ,temp) ;
scanf("%s" ,word) ;
printf("%d\n", KMP_Count(temp , strlen(temp) , word , strlen(word))) ;
}
return 0 ;
}