想改行的林 2021-05-25 23:45 采纳率: 100%
浏览 133
已采纳

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

  • 写回答

2条回答 默认 最新

  • 想改行的林 2021-05-28 18:51
    关注

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

    j==-1应该在前面

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?