您的位置:首页 > 其它

kmp字符串匹配算法

2009-04-29 23:27 423 查看
#include<iostream>
#include<string>
using namespace std;

//定义KMP算法系统
class KMP_Sys
{
private:
//主串
string P_data;
//模式串
string S_data;
//next值的整型指针
int *next;
//nextval值的整型指针
int *nextval;
//模式串在主串,0为不存在
int pos;
//KMP核心算法
void KMP_Index(int *next)
{
int i = 1;
int j = 1;
while(i <= int(P_data.size() - 1) && j <= int(S_data.size()) - 1)
{
//继续比较后继字符
if(j == 0 || P_data[i] == S_data[j])
{
++i;
++j;
}
//模式串向右移动
else
j = next[j];
}
//匹配成功
if (j > int(S_data.size()) - 1)
pos =  i - int(S_data.size()) + 1;
//匹配不成功
else
pos = 0;

}

public:
//初始化KMP系统
KMP_Sys()
{
//因为字符串从1位置开始匹配,所以0位置赋值为空格
P_data = " ";
S_data = " ";
//next与nextval均为长度256的数组
next = new int[256];
nextval = new int[256];
}
~KMP_Sys()
{
//回收动态申请空间
delete next;
delete nextval;
}
//求模式串的next值
void GetNext()
{
int i = 1;
next[1] = 0;
int j = 0;
while(i < int(S_data.size()) - 1)
{
if(j == 0 || S_data[i] == S_data[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}

}
//求模式串的nextval值
void GetNextval()
{
int i = 1;
nextval[1] = 0;
int j = 0;
while(i < int(S_data.size()) - 1)
{
if(j == 0 || S_data[i] == S_data[j])
{
++i;
++j;
if(S_data[i] != S_data[j])
nextval[i] = j;
else
nextval[i] = nextval[j];
}
else
j = nextval[j];
}
}
//KMP系统的运行实体
void run()
{
cout << "主串:";
string s1, s2;
getline(cin, s1);
P_data = P_data + s1;
cout << "模式串:";
getline(cin, s2);
S_data = S_data + s2;
//模式串输入后分别求它的next与nextval值
GetNext();
GetNextval();
cout << "next值:";
//输出next值
for(int i = 1; i <= int(S_data.size()) - 1; i++)
cout << next[i];
cout << endl;
//输出nextval值
cout << "nextval值:";
for(int i = 1; i <= int(S_data.size()) - 1; i++)
cout << nextval[i];
cout << endl;
KMP_Index(next);
cout << "位置:" << pos << endl;
}

};
void main()
{
KMP_Sys kmp;
//运行KMP系统
kmp.run();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 string delete class