思路
1.字符串中的一个字符(连续相同的字符作1个字符)
2.依次对比字符两侧字符是否相等
代码
char* longestPalindrome(char* s) {
int max = 1;
int left, right;
int maxLeft = 0;
int totalLen = strlen(s);
int i;
char *res = (char *) calloc(1, 1001);
if(totalLen == 1) {
res[0] = s[0];
return res;
}
for(i = 0; i < totalLen - 1;) {
if(totalLen-i<=max/2)//剩余长度小于当前最大长度,则没有查找下一个的必要
break;
//first, pass consecutive numbers equal to each other
right = i;
left = i;
while((right < totalLen - 1) && (s[right] == s[right + 1])) {
right ++;
}
//second, set i = r + 1, for there is no len larger when start from i to r
i = right + 1;
//third, count those s[right] == s[left]
while((left > 0) && (right < totalLen - 1) && (s[left - 1] == s[right + 1])) {
right++;
left--;
}
if(right - left + 1 > max) {
maxLeft = left;
max = right - left + 1;
}
}
strncpy(res, s + maxLeft, max);
return res;
}