您的位置:首页 > 理论基础 > 数据结构算法

SDUT 2272 数据结构实验之串一:KMP简单应用

2016-06-19 15:36 423 查看
点击打开题目链接

#include <bits/stdc++.h>
#define N 1000010
using namespace std;

int next
;
char _string1
, _string2
;
int _find(char *str1, char *str2);
void creat_next(char *str);

int main()
{

while(gets(_string1))
{
gets(_string2);
creat_next(_string2);
cout << _find(_string1, _string2) << endl;
}
return 0;
}

void creat_next(char *str)
{
int lenth = strlen(str);
int j = -1, k = 0;
next[0] = -1;
while(k < lenth)
{
if(j == -1 || str[j] == str[k])
{
++ j;
++ k;
next[k] = j;
}
else
{
j = next[j];
}
}
}

int  _find(char *str1, char *str2)
{
int lenth1 = strlen(str1), lenth2 = strlen(str2);
int i = 0, j = 0;
while(i < lenth1 && j < lenth2)
{
if(j == -1 || str1[i] == str2[j])
{
++ j;
++ i;
}
else
j = next[j];
}
if(str2[j] == '\0')
{
return i-lenth2+1;
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kmp