字符串的查找--KMP算法

来源:互联网 发布:单页源码 编辑:程序博客网 时间:2024/06/10 21:00
#include<iostream>
#include<string>
using namespace std;


 int* get_next(string& s) 

{
int i = 0, j = -1;
int* next = new int[s.size()];
next[0] = -1; 


while (i < s.length() - 1)
{
if (j == -1 || s[i]==s[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
return next;
}


int kmp_index(string &Tag,  string& Ptn, int pos)
{
int* next = get_next(Ptn);
int i = pos;  
int j = 0;   
int Tlen = Tag.size();  
int Plen = Ptn.size();  


while (i < Tlen && j < Plen)
{
if (j == -1 || Tag[i] == Ptn[j])
{  
i++;
j++;
}
else   
{
j = next[j];
}
}


if (j >= Plen)
return i - Plen;
else
return -1;
}




//测试程序:
int main()
{
char ch;
do{
string Tag, Ptn;
int pos;
cout << "输入主串:";
cin >> Tag;
cout << "输入子串:";
cin >> Ptn;
cout << "输入主串中开始进行匹配的位置(首字符位置为0):";
cin >> pos;


int result = kmp_index(Tag, Ptn, pos);
if (result != -1)
cout << "主串与子串在主串的第" << result << "个字符(首字符的位置为0)处首次匹配" << endl;
else
cout << "无匹配子串" << endl;


cout << "是否继续测试(输入y或Y继续,任意其他键结束):";
cin >> ch;
} while (ch == 'y' || ch == 'Y');
return 0;
}

0 0
原创粉丝点击