经典算法题--求对策字符串的最大长度
题目:输入一个字符串,输出该字符串对称子字符串的最大长度,如输入google,则输出4.
思路:思路很中规中矩,遍历这个字符串,若有发现相邻的两个字符相等,就循环判断与这两个字符相邻的两个字符是否相等,
直到不等,记下字符符合条件的字符个数。最大的个数即为所求。
class Program
{
static void Main(string[] args)
{
string str = "google";
int strLen = counterplan1(str);
Console.WriteLine(strLen);
Console.ReadKey();
}
public static int counterplan1(string str)
{
int strlen = str.Length;
int maxlen = 0;
for (int i = 0; i < strlen-1; i++)
{
if (str[i] == str[i + 1])
{
int start = i - 1;
int end = i + 2;
while (start >= 0 && end < strlen)
{
if (str[start] == str[end])
{
--start;
++end;
}
else
{
break;
}
}
if (maxlen < end - start-1)
{
maxlen = end - start-1;
}
}
}
return maxlen;
}
}