题目要求:
输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串"google",由于该字符串里最长的对称子字符串"goog",因此输出4.
题目分析:
代码实现:
#include <stdio.h>
int LongestPalindrome(const char *s, int n);
int main(void )
{
printf( "%d\n",LongestPalindrome("abcddcbav" ,9));
return 0;
}
int LongestPalindrome(const char *s, int n)
{
int i, j, max;
if (s == 0 || n < 1) return 0;
max = 0;
// i is the middle point of the palindrome
for (i = 0; i < n; ++i)
{
for (j = 0; (i-j >= 0) && (i+j < n); ++j) // if the length of the palindromeis odd
{
if (s[i-j] != s[i+j])
{
break ;
}
}
j--;
if (j*2+1 > max)
max = j * 2 + 1;
for (j = 0; (i-j >= 0) && (i+j+1 < n); ++j) // for the even case
{
if (s[i-j] != s[i+j+1])
{
break ;
}
}
j--;
if (j*2+2 > max) max = j * 2 + 2;
}
return max;
}