按算法导论字符串匹配章节描述,用C++实现了其中2种算法:朴素字符串匹配算法和KMP匹配算法。
class my_string
{
public:
my_string() : length(0){}
my_string(const char* str)
{
length = strlen(str);
memcpy(buf, str, length);
buf[length] = '\0';
}
char buf[256];
int length;
};
int naive_string_matcher(my_string& t, my_string& p)
{
if (t.length < p.length)
{
return -1;
}
int n = t.length;
int m = p.length;
for (int s = 0; s <= n - m; ++s)
{
if (0 == memcmp(t.buf + s, p.buf, m))
{
return s;
}
}
return -1;
}
int* compute_prefix_func(my_string& p)
{
int m = p.length;
int* pi = new int[m];
pi[0] = 0;
int k = 0;
for (int q = 1; q < m; ++q)
{
while (k > 0 && p.buf[k] != p.buf[q])
{
k = pi[k - 1];
}
if (p.buf[k] == p.buf[q])
{
++k;
}
pi[q] = k;
}
return pi;
}
int kmp_matcher(my_string& t, my_string& p)
{
if (t.length < p.length)
{
return -1;
}
int n = t.length;
int m = p.length;
int* pi = compute_prefix_func(p);
int q = 0;
for (int i = 0; i < n; ++i)
{
while (q > 0 && p.buf[q] != t.buf[i])
{
q = pi[q - 1];
}
if (p.buf[q] == t.buf[i])
{
++q;
}
if (q == m)
{
delete[]pi;
return i - m + 1;
}
}
delete[]pi;
return -1;
}