//头文件
#ifndef KMP_H
#define KMP_H
#include
#include
using namespace std;
class kmp{
private:
string value, pString;
int *pStr;//特征向量
public:
void setValue();
string getValue();
void getpStr();
bool KMPMatch();
void simulate();
};
void kmp::setValue()
{
cout << "input the value: ";
cin >> value;
cout << "input the pString: ";
cin >> pString;
}
string kmp::getValue()
{
return pString;
}
void kmp::getpStr()
{
//开辟特征向量空间的大小,并将第一个字符的特征向量定为0
int count = this->pString.length();
pStr = new int[count];
pStr[0] = 0;
int k = 0;
for (int i = 1; i < count; i++)
{
//在匹配字符串的预处理时期,最终要的是要看前一个字符的特征向量出的值
//然后将要比较的字符和pStr[k]处的字符相比较,如果相同则该位置的特征向量等于前一位置的特征向量加一
//如果前一位置的特征向量=0,但是当前位置的字符与pStr[k]即pStr[0]的字符相等,当前位置的特征向量=k+1
//如果k=0,且当前位置与pStr[k]即pStr[0]的字符不相等,则此处的特征向量值等于0
k = pStr[i - 1];
while (k>0 && this->pString[i] != this->pString[k])
k = pStr[k - 1];
if (this->pString[i] == this->pString[k])
pStr[i] = k + 1;
else
pStr[i] = 0;
}
}
bool kmp::KMPMatch()
{
int count = this->value.length();
int number = this->pString.length();
if (number > count)
return false;
int i = 0, j = 0;
while (i < count&&j < number)
{
if (this->value[i++] == this->pString[j])
{
//i++必须写在this->value[i++]中,否则会出现字符串长度长是的死循环现象
j++;
}
else
{
//此时,出现字符不相等的情况,开始查看该位置处的特征向量,然后将要查找的字符串的位置移到
//特征向量所指向的位置,而模式字符串则不发生变化即j的值不发生变化
j = pStr[j];
}
}
//如果j>=number则说明匹配成功
if (j >= number)
return true;
return false;
}
void kmp::simulate()
{
bool flag = true;
while (flag)
{
this->setValue();
this->getpStr();
flag = this->KMPMatch();
if (flag)
{
cout << "succeed" << endl;
}
else
cout << "failer" << endl;
}
}
#endif
//主函数
#include"kmp.h"
int main(int argc, char argv[])
{
kmp user;
user.simulate();
return 0;
}
kmp字符串匹配算法
最新推荐文章于 2022-11-02 11:02:56 发布