BF算法
时间复杂度:O(n*m) n表示主串的长度,m表示子串的长度 空间复杂度:O(1) 匹配串 A(“abcac”)是否为串 B(“ababcabacabab”)子串: 第一次: 第二次: 第三次: 直到第六次匹配成功:
代码1
#include<iostream>
using namespace std;
//返回子串在主串中的索引
int BF(string s, string t)
{
int i = 0;
int j = 0;
while (i < s.size() && j < t.size()) // O(n)
{
if (s[i] == t[j])
{
i++;
j++;
}
else
{
i = i - j + 1; // 复位i,指向之前开始匹配字符的下一个字符 O(m)
j = 0;
}
}
if (j == t.size()) // 找到了
{
return i - j;
}
else
{
return -1;
}
}
int main() {
string s = "ababcabcacbab";
string t = "abcac";
//返回子串在主串中的索引
int pos = BF(s, t);
cout << pos << endl;
return 0;
}
代码2
#include <iostream>
using namespace std;
int brute_force(const char* text, const char* pattern)
{
for (int i = 0; text[i]; ++i)
{
int flag = 1;
for (int j = 0; pattern[j]; ++j)
{
if (text[i + j] == pattern[j]) continue;
flag = 0;
break;
}
if (flag) return i;
}
}
#define TEST(func,s1,s2){ \
printf("%s(\"%s\",\"%s\")=%d\n",#func,s1,s2,func(s1,s2)); \
}
int main()
{
char s1[100]= "ababcabcacbab";
char s2[100]= "abcac";
TEST(brute_force, s1, s2);
return 0;
}
KMP
#include <iostream>
using namespace std;
void GetNext(const char* pattern, int* next)
{
next[0] = -1;
for (int i = 1, j = -1; pattern[i]; ++i)
{
while (j != -1 && pattern[j + 1] - pattern[i]) j = next[j];
if (pattern[j + 1] == pattern[i]) j += 1;
next[i] = j;
}
return;
}
int kmp(const char* text, const char* pattern)
{
int n = strlen(pattern);
int* next = (int*)malloc(sizeof(int) * n);
GetNext(pattern, next);
for (int i = 0, j = -1; text[i]; ++i)
{
while (j != -1 && text[i] - pattern[j + 1]) j = next[j];
if (text[i] == pattern[j + 1]) j += 1;
if (pattern[j + 1] == 0) return i - j;
}
return -1;
}
#define TEST(func,s1,s2){ \
printf("%s(\"%s\",\"%s\")=%d\n",#func,s1,s2,func(s1,s2)); \
}
int main()
{
char s1[100] = "ababcabcacbab";
char s2[100] = "abcac";
TEST(kmp, s1, s2);
return 0;
}