一、朴素匹配算法
#include<bits/stdc++.h>
using namespace std;
// 返回s2在s1中出现的次数
int StringCompare(char s1[], char s2[])
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int count = 0;
for (int i = 0; i <= len1 - len2 + 1; i++)
{
bool flag = 1;
for (int j = 0; j < len2; j++)
{
if (s1[i + j] != s2[j])
{
flag = 0;
break;
}
}
if (flag == 1)
{
count++;
}
}
return count;
}
int main()
{
char s1[1000];
char s2[1000];
cin >> s1 >> s2;
cout << StringCompare(s1, s2) << endl;
return 0;
}
/*
测试
aaabbaaaaaaaba aaaba
AGAAAGTTCGGAA GA
*/
二、KMP匹配算法
#include<bits/stdc++.h>
using namespace std;
// 计算next数组
int * Next(char s2[])
{
int * next = new int[strlen(s2)];
int i = 0, j = -1;
next[0] = -1;
while(i < strlen(s2) - 1)
{
// 找出最大相同后缀子串和前缀子串
while(j >= 0 && s2[i] != s2[j])
{
j = next[j];
}
i++;
j++;
if (s2[i] == s2[j])
{
next[i] = next[j];
}
else
{
next[i] = j;
}
}
return next;
}
// 返回s2在s1中出现的次数
int KMPCompare(char s1[], char s2[])
{
int count = 0;
int i, j;
int * next = Next(s2);
for (i = 0, j = 0; j < strlen(s1);)
{
if (s2[i] == s1[j])
{
i++;
j++;
}
else if (next[i] >= 0)
{
i = next[i];
}
else
{
i = 0;
j++;
}
if (i >= strlen(s2))
{
count++;
j++;
}
}
return count;
}
int main()
{
char s1[1000];
char s2[1000];
cin >> s1 >> s2;
cout << KMPCompare(s1, s2) << endl;
return 0;
}
/*
测试
aaabbaaaaaaaba aaaba
AGAAAGTTCGGAA GA
*/