您的位置:首页 > 其它

第七十三题(对称字符串的最大长度)

2014-07-08 21:48 204 查看
73.对称字符串的最大长度。

题目:输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。

这里采用复杂度为O(n^2)的方法,具体实施方式为设置下标i遍历字符串,然后以每个位置i处字符为中心向两边同时遍历,直到两边字符不相等推出循环,记录循环的次数,由循环的次数计算出对称字符串的长度。

对称字符串长度可能为奇数也可能为偶数,需要区别对待。

程序:

namespace MS100P_73
{
	int maxSymmetricLength(const char* str)
	{
		if (str == NULL)	return 0;
		int len = strlen(str);
		int i = 0, j = 0, maxLength = 1;
		while (i < len)
		{
			//先处理对称字符串为偶数的情况
			for (j = 0; i - j >= 0 && i + j + 1 < len; j++)
			if (str[i - j] != str[i + j + 1])
				break;
			if (maxLength < 2 * j)	maxLength = 2 *j;
			//再处理对称字符串为奇数的情况
			for (j = 0; i - j >= 0 && i + j < len; j++)
			if (str[i - j] != str[i + j])
				break;
			if (maxLength < 2 * j - 1)	maxLength = 2 * j - 1;

			i++;
		}
		return maxLength;
	}
	void test()
	{
		const char* str = "google";
		cout << maxSymmetricLength(str) << endl;
		str = "goeaeogle";
		cout << maxSymmetricLength(str) << endl;
		str = "hhh";
		cout << maxSymmetricLength(str) << endl;
		str = "hh";
		cout << maxSymmetricLength(str) << endl;
	}
}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: