64,654
社区成员
发帖
与我相关
我的任务
分享
int instr(char *source, char *pattern)
{
char *tmp=NULL;
tmp = strstr(source, pattern);
if(tmp == NULL)
return(-1);
else
return((source > tmp) ? (source - tmp + 1) : (tmp - source + 1));
}
#include <iostream>
#include <tchar.h>
#include <windows.h>
using namespace std;
void KMP_GetNextVal(const TCHAR* pattern, int next[])
{
int j = 0, k = -1;
next[0] = -1;
while (pattern[j] != _T('\0'))
{
if (k == -1 || pattern[j] == pattern[k])
{
++j;
++k;
if (pattern[j] != pattern[k])
next[j] = k;
else
next[j] = next[k];
}
else
k = next[k];
}
}
int KMP_Find(const TCHAR* text, const TCHAR* pattern, const int patternLen)
{
if (!text || !pattern || pattern[0] == _T('\0') || text[0] == _T('\0'))
return -1;
int next[patternLen];
KMP_GetNextVal(pattern, next);
int index = 0, i = 0, j = 0;
while (text[i] != _T('\0') && pattern[j] != _T('\0'))
{
if (text[i] == pattern[j])
{
++i;
++j;
}
else
{
index += j - next[j];
if (next[j] != -1)
j = next[j];
else
{
j = 0;
++i;
}
}
}
if (pattern[j] == _T('\0'))
return index;
else
return -1;
}
int main()
{
const TCHAR* s1 = _T("jhefiektju2fwjq3n3the");
const TCHAR* s2 = _T("fwjq3");
cout << KMP_Find(s1, s2, lstrlen(s1)) << endl;
return 0;
}