您的位置:首页 > 其它

kmp算法实现字符串匹配

2016-10-24 23:51 471 查看
今天晚上知道了这个算法,看了后凭记忆理解自己又写了一遍,日后会加上注释和思路

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
void find_fun(string pstr, int *num){
int i;
int len = pstr.length();
int index;
//int* num = new int[len + 1];
num[0] = -1;
for (i = 1; i < len; i++)
{
index = num[i - 1];
if (pstr[i] != pstr[index + 1] && index >= 0){
index = -1;
}
if (pstr[i] == pstr[index + 1])
{
index++;
num[i] = index;
}
else
{
num[i] = -1;
}
}
num[i] = '\0';
for (i = 0; i < len; i++){
cout << num[i] << " ";
}
cout << endl;
}
int main(){
while (true){
string pstr="";
string str="";
int i, j;
cout << "输入目标字符串:" << endl;
cin >> pstr;
cout << "输入源字符串:" << endl;
cin >> str;
if (pstr == "end")
break;
int len = pstr.length();
int n = str.length();
int* num = new int[len + 1];
find_fun(pstr, num);
for (i = 0,j=0; (i < n)&&(j<len); )
{
if (pstr[j] == str[i])
{
j++;
i++;

}
else
{
if (j == 0)
{
i++; j++;

}
else
{
j = num[j - 1] + 1;
}
}
}
if (j == (len)){
cout << "匹配成功,索引在:" << i-len << endl << "str[i-1-len]==" << str[i-len] << endl;
}
else
cout << "匹配不成功" << endl;

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: