暴力解法
思路
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;
}