#include<stdlib.h>
#include<stdio.h>
int main()
{
char* longestPalindrome(char* s);
char s[] = "erwwr";//任写
char* c = longestPalindrome(s);
printf("%s\n", c);
}
char* longestPalindrome(char* s) {
int expend1 = 0, max1 = 0;
int index1 = 0, index2 = 0;//记录下最大子串的长度
int count1 = 0, maxLength1 = 0;
int k1, i, g1;
int count_x = 0;//计算出字符串长度
/*计算奇数时的情况*/
for (i = 0; s[i] != '\0'; i++, count_x++)
{
k1 = i, g1 = i;//分别从中心位置扩散
count1 = 0; expend1 = 0;
while ((s[k1] == s[g1]) && s[k1] && g1 >= 0)
{
++count1; //计算字符个数
++expend1;
k1 = i + expend1; //向后扩散
g1 = i - expend1; //向前扩散
}
if (count1 > max1) {
max1 = count1;
index1 = g1 + 1;
index2 = k1 - 1;
maxLength1 = index2 - index1 + 1;//求出最大长度
}
}
/*计算偶数时的情况*/
int count2 = 0, expend2 = 0, max2 = 0, maxLength2 = 0;
int index3 = 0, index4 = 0;//记录下最大子串的长度
int j, g2, k2;
for (j = 0; j < count_x - 1; j++) {
g2 = j, k2 = j + 1;//分别从两个位置扩散
count2 = 0; expend2 = 0;
while ((s[g2] == s[k2]) && g2 >= 0 && s[k2])
{
++count2;
++expend2;
g2 = j - expend2; //向后扩散
k2 = j + 1 + expend2;//向前扩散
}
if (count2 > max2) {
max2 = count2;
index3 = g2 + 1;
index4 = k2 - 1;
maxLength2 = index4 - index3 + 1;//求出最大长度
}
}
/*判断奇数还是偶数子串大*/
int y = 0, h;
if (max1 > max2)
{
char* c = (char*)malloc(maxLength1 + 1);
if (c) {
for (h = index1; h <= index2; h++)
{
c[y++] = s[h];
}
c[y] = '\0';
}
return c;
}
else {
char* c = (char*)malloc(maxLength2 + 2);
if (c) {
for (h = index3; h <= index4; h++)
{
c[y++] = s[h];
}
c[y] = '\0';
}
return c;
}
}
用 简单c语言 ~求出最长回文子串
最新推荐文章于 2023-06-24 16:54:17 发布