#include<iostream>
using namespace std;
#include <string>
int Index(string S, string T)
{
int i = 0;
int j = 0;
while (i <(int) S.length() && j< (int)T.length())
{
if (S[i] == T[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == T.length()) { return i - j; }
else { return -1; }
}
int* GenNext(string T)
{
int* next = new int[(int)T.length()+1];
int i = 0; int j = -1;
next[0] = -1;
int length = (int)T.length();
while (i <length-1)
{
if (j == -1 || T[i] == T[j])
{
//next[i + 1] = next[i] + 1;
//next[i+1]=j +1;这个太晦涩了next[i]=j
next[++i] = ++j;//或者放在++之后,这样更晦涩
//pro版
//next[i] = ((T[i] == T[next[i]]) ? next[j] : j);
//next[i] = ((T[i] == T[j]) ? next[j] : j);
}
else
{
j = next[j];
}
}
return next;
};
int IndexKMP(string S, string T)
{
int* next = GenNext(T);
int i = 0; int j = 0;
while (i < (int)S.length() && j < (int)T.length())
{
if (S[i] == T[j]||j==-1)
{
i++;
j++;
}
else
{
j = next[j];
}
}
delete next;
return (j == (int)T.length()) ? i - j : -1;
}
int main()
{
string S;
S = "FAFSAFAEW";
string T;
T = "DFAFEFDSF";
cout << IndexKMP(S, T) << endl;
system("pause");
return 0;
}
问题1:为什么这里提示我内存溢出?
问题2:运行就崩,字符串越界。