您的位置:首页 > 其它

【字符串】KMP算法的实现

2015-06-02 11:07 323 查看
来源:脑客爱刷题

vector<int> GetNextArr(const string &match)
{
	vector<int> NextArr;
	if (match.empty())
		return NextArr;
	if (match.size() == 1)
		return vector<int>(1, -1);

	NextArr = vector<int>(match.size());
	NextArr[0] = -1;//规定res[0]=-1
	NextArr[1] = 0;
	int cn = 0,i=2;//cn记录着上一轮计算得到的最长匹配前缀的长度,i是match的下标
	while (i < match.size())
	{
		if (match[i - 1] == match[cn])
		{
			NextArr[i] = cn + 1;
			++i;
			++cn;
		}
		else if (cn>0)
			cn = NextArr[cn];
		else // cn==0
		{
			NextArr[i] = 0;
			++i;
		}
	}
	return NextArr;
}

int KMP(const string &str, const string &match)
{
	if (match.empty())
		return 0;
	if (str.size() < match.size())
		return -1;
	vector<int> NextArr = GetNextArr(match);
	int i = 0, i_match = 0;
	while (i < str.size() && i_match < match.size())
	{
		if (str[i] == match[i_match])
		{
			++i;
			++i_match;
		}
		else if (i_match == 0)
		{
			
			++i;
		}
		else
		{
			i_match = NextArr[i_match];
		}
	}
	if (i_match == match.size())
		return i - match.size();
	else
		return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: