最长对称字符串问题
问题描述:
输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。
#include <stdio.h>
#include <string.h>
#define N 10
int Find_len(char a[], int &max_len);
int Symmetry(char a[], int low, int high);
int main()
{
char a[] = "abcdlgooogle";
int start_pos = 0;
int max_len = 1;
int i = 0;
start_pos = Find_len(a, max_len);
printf("%s\n", a);
printf("Max_len = %d\n", max_len);
printf("The max length symmetry string is ");
for (i = 0; i < max_len; i++)
{
printf("%c", a[start_pos + i]);
}
printf("\n");
return 0;
}
int Symmetry(char a[], int low, int high)
{
if((low < 0) || (low > high))
{
return -1;
}
int i = low;
int j = high;
for (; i < j; i++, j--)
{
if (a[i] != a[j])
{
return 0;
}
}
return 1;
}
int Find_len(char a[], int &max_len)
{
if (NULL == a)
{
return 0;
}
int len = 0;
len = strlen(a);
if (len == 1)
{
return 1;
}
int i = 0;
int j = 0;
int start_pos = 0;
max_len = 1;
for (i = 0; (i < len) && ( max_len < (len - i) ); i++)
{
for (j = len - 1; j > i; j--)
{
int result = 1;
result = Symmetry(a, i, j);
if (result)
{
if( max_len < (j - i + 1))
{
max_len = j - i + 1;
start_pos = i;
}
break;
}
}
}
return start_pos;
}