暴力解法
思路
1、做一个子函数,用于检测输入的字符串是否是回文串
2、使用双指针,头指针从字符串开始处遍历,尾指针每次均从结尾处开始,检查头尾指针之间的字符串是否是回文串,若是,且长度大于之前的长度,则更新,否则进行下次检查,注意,大循环的结束条件可以随着找到回文子串的长度而更新。
代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // for malloc(), free()
#define YES 1
#define NO 0
int IsPalindrome(char *strIn,int strLength)
{
for (int i = 0; i < strLength/2; i++) {
if (strIn[i] != strIn[strLength - 1 - i]) {
return NO;
}
}
return YES;
}
char * longestPalindrome(char * s)
{
int strLength = strlen(s);
if (strLength < 2) {
return s;
}
char tmpLongestPald[1001] = {0};
tmpLongestPald[0] = s[0];
int maxLength = 1;
int endIndex;
for (int i = 0; i < strLength - maxLength; i++) {
endIndex = strLength - 1;
while (endIndex - i+1 > maxLength) {
if (IsPalindrome(s+i,endIndex-i+1)==YES) {
if (endIndex - i + 1>maxLength) {
maxLength = endIndex - i + 1;
memcpy(tmpLongestPald, s + i, maxLength);
}
break;
} else {
endIndex--;
}
}
}
char* strRet;
strRet = (char*)malloc(maxLength+1);
strcpy(strRet,tmpLongestPald);
return strRet;
}
优化
思路
1、从字符串头开始遍历
2、找到最小子串后,依次向外扩展
3、最小子串有两种形式 bb 或者 aba
4、根据找到的最大长度选择是否提前结束循环
代码
char * longestPalindrome(char * s)
{
int strLength = strlen(s);
if (strLength < 2) {
return s;
}
char tmpLongestPald[1001] = {0};
tmpLongestPald[0] = s[0];
int maxLength = 1;
int sideSize = 0;
for (int i = 0; i < strLength - maxLength/2; i++) {
sideSize = 0;
while ((i-sideSize >= 0) && (i + sideSize + 1 < strLength))
{
if (s[i-sideSize] == s[i+sideSize+1]) {
sideSize++;
} else {
break;
}
}
if (maxLength < 2 * sideSize) {
maxLength = 2 * sideSize;
memcpy(tmpLongestPald, s+i-sideSize+1, maxLength);
}
sideSize = 1;
while ((i-sideSize >= 0) && (i + sideSize < strLength))
{
if (s[i-sideSize] == s[i+sideSize]) {
sideSize++;
} else {
break;
}
}
if (maxLength < 2 * sideSize - 1 ) {
maxLength = 2 * sideSize - 1;
memcpy(tmpLongestPald, s+i-sideSize+1, maxLength);
}
}
char* strRet;
strRet = (char*)malloc(maxLength+1);
strcpy(strRet,tmpLongestPald);
return strRet;
}
来源:CSDN
作者:NjustMEMS_ZJ
链接:https://blog.csdn.net/u013098336/article/details/104342799