先把代码记下来,以后有时间再把分析补上
/*
*String.h
*/
class String
{
private:
char * str;
int size;
public:
String(char * str);
int getsize();
char * getstr();
~String();
void CptPfFunc(int * prefix);
void KMPstrMatching(String &str, int * prefix, int * result);
};
/*
*String.cpp
*/
#include "String.h"
#include<string.h>
String::String(char * str)
{
this->str = new char[100];
strcpy(this->str,str);
this->size = strlen(this->str);
}
int String::getsize()
{
return size;
}
char * String::getstr()
{
return str;
}
/*
* 查找是真后缀的最大前缀
*/
void String::CptPfFunc(int * prefix)
{
prefix[1] = 0;
int LOLP = 0;
for(int NOCM = 2; NOCM <= strlen(str); NOCM++)
{
while(LOLP > 0 && str[LOLP] != str[NOCM - 1])
LOLP = prefix[LOLP];
if(str[LOLP] == str[NOCM - 1])
LOLP++;
prefix[NOCM] = LOLP;
}
}
void String::KMPstrMatching(String &str, int * prefix, int * result)
{
int NOCM = 0;
int j = 0;
int length_pattern = str.getsize();
for(int i = 0; i < this->size; i++)
{
while(NOCM > 0 && (str.getstr())[NOCM] != (this->str)[i])
NOCM = prefix[NOCM];
if((str.getstr())[NOCM] == (this->str)[i])
NOCM++;
if(NOCM == length_pattern)
{
result[j] = i - length_pattern + 1;
j++;
NOCM = prefix[NOCM];
}
}
}
String::~String()
{
delete str;
}
/*
*main.cpp
*/
#include<iostream>
#include "String.h"
using namespace std;
int main()
{
char tar[30] = "abccabccabcabccabccabcabcc";
char pat[30] = "abccabccabca";
int prefix[30];
int result[30];
String target(tar);
String pattern(pat);
pattern.CptPfFunc(prefix);
target.KMPstrMatching(pattern, prefix, result);
return 0;
}