string subscript out of range

#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:运行就崩,字符串越界。

啥也不是,我自己解决了,

j==-1应该在前面

我把79行的

system("pause");

去掉后可以运行,结果是-1

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632