定长顺序串的kmp算法

来源:互联网 发布:苹果5s2g网络怎么改4g 编辑:程序博客网 时间:2024/05/19 13:59
#include <iostream>
#include <cstring>
using namespace std;
#define MAXSTRLEN 200
#define TRUE 1
#define FALSE 0
#define  OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef unsigned char sstring[MAXSTRLEN + 1];
int strassig(sstring &T, char chars[])//赋值操作 
{
int i;
if (strlen(chars)>MAXSTRLEN)
return ERROR;
else
{
T[0] = strlen(chars);
for (i = 0; i<strlen(chars); i++)
T[i + 1] = chars[i];
}
return OK;


}


void get_next(sstring T, int next[])
{
int i = 1, j = 0;
next[1] = 0;
while (i<T[0])
{
if (j == 0 || T[i] == T[j])
{
++i;
++j;
next[i] = j;
}
else j = next[j];
}
}


int index_kmp(sstring s, sstring T, int pos, int next[])
{
int i = pos, j = 1;
while (i <= s[0] && j <= T[0])
{
if (j == 0 || s[i] == T[j])
{
++i;
++j;
}
else j = next[j];
}
if (j>T[0])
return i - T[0];
else return 0;
}
void shuchu(sstring s)
{
for (int i = 1; i <= s[0]; i++)
cout << s[i];
cout << endl;
}
int main()
{
int i, m, n,next[6];
sstring T, s, sub;
char chars1[18] = { 'a', 'c', 'a', 'b', 'a', 'a', 'b', 'a', 'a', 'b','c','a','c','a','a','b','c' };
char chars2[7] = { 'a', 'b', 'a', 'a', 'b', 'c'};
strassig(s, chars1);
cout << "将chars1的值赋予s:";
shuchu(s);
cout << "将chars2的值赋予T:";
strassig(T, chars2);
shuchu(T);
get_next(T, next);
cin >> m;
if (index_kmp(s, T, m, next) == 0)
cout << "在字符串s的第" << m << "个字符之后,没有与子串T相照应的子串" << endl;
else
cout << "在字符串s中,与子串T照应的子串位于第" << m << "个字符之后的第" << index_kmp(s, T, m, next) - m <<"个位置"<<endl<<endl;
system("pause");
return 0;
}
0 0
原创粉丝点击