1. 题目描述
难度:中等
2. 题目分析
根据题目,需要注意的有以下几点:
- 回文子串
回文子串就是正着读和反着读是一样的,比如abcba,就是回文子串。 - 有效答案不止一个
如题中所示的,答案可能有多个,但是输出其中一个就好。
本题的解法是滑动窗口法:
- 滑动窗口法
滑动窗口法就是从大到小遍历各种大小的窗口,然后判断窗口中的字符串是否为回文串,如果是,返回该窗口的字符串即可。该算法的时间复杂度为O(n^2)。
3. C语言实现
代码如下:
// 寻找特定窗口下是否有回文子串,如果有,返回1,如果没有,返回0
int findstr(char *s, int index, int size, char *str){
int i, j;
// 定义窗口的起始点和结束点
i = index;
j = index + size -1;
while(i <= j){
if(s[i] == s[j]){
i++;
j--;
}
else{
break;
}
}
if(i >= j){
j = index;
for(i = 0; i < size; i++){
str[i] = s[j];
j++;
}
return 1;
}
return 0;
}
char * longestPalindrome(char * s){
int index, len, size, i;
char* str = (char *)malloc(sizeof(char)*1000);
char *res;
str[0] = ' ';
str[999] = '\0';
len = strlen(s);
for(size = len; size > 0; size--){
for(index = 0; index <= len-size; index++){
if(findstr(s, index, size, str)){
res = (char *)malloc(sizeof(char)*(size+1));
for(i = 0; i < size; i++) res[i] = str[i];
res[size] = '\0';
return res;
}
}
}
return res;
}
运行结果为: