现在的位置: 首页 > 综合 > 正文

求对称字符串的最大长度

2013年07月26日 ⁄ 综合 ⁄ 共 628字 ⁄ 字号 评论关闭
//返回最长的对称字符串的长度,如google,对称字符串是goog,最大长度为4
int symStr(char* source)
{
	if('\0' == *source)
		return 0;
	int maxLength = 1;
	char* current = source;
	while('\0' != *current)
	{
		int max1 = 0;
		int symIndex = 0; // 对称游标
		//(1) googllgox,对称字符个数为偶数,比如这样返回6,此时current + i + 1
		while('\0' != *(current - symIndex - 1) && '\0' != *(current + symIndex) &&
			*(current - symIndex - 1) == *(current + symIndex))
		{
			max1 += 2;
			symIndex++;
		}
		maxLength = max(max1, maxLength);
		max1 = 1;
		symIndex = 1;
		//(2)baidudiac,对称字符个数为奇数,比如这样返回7
		while('\0' != *(current - symIndex) && '\0' != *(current + symIndex) &&
			*(current - symIndex) == *(current + symIndex))
		{
			max1 += 2;
			symIndex++;
		}
		maxLength = max(max1, maxLength);
		++current;
	}
	return maxLength;
}

代码还有很多改进的地方,留给读者自由发挥

抱歉!评论已关闭.