manacher算法的实现

manacher算法的解释见 这里。


//求字符串s中最大回文的长度,要求字符串s不包含字符‘#’
int manacher(const string &s)
{
	if (s.size() <= 1)
		return s.size();

	//往s每个字符之间以及s的首尾都插入‘#’
	string str(s.size() * 2 + 1, '#');
	for (int i = 0, j = 1; i p(size, 1);
	p[1] = 2;

	for (int i = 2; i <= size-3; ++i)
	{
		int maxright = p[id] + id - 1;
		if (i>maxright)
		{
			while (i - p[i] >= 0 && i + p[i]idleft)
				p[i] = p[j];
			else if (tmp= 0 && i + p[i]p[id] + id)
			id = i;
		maxr = max(maxr, p[i]);
	}

	return maxr - 1;

}


你可能感兴趣的:(程序员面试题)