思路
1.字符串中的一個字符(連續(xù)相同的字符作1個字符)
2.依次對比字符兩側(cè)字符是否相等
代碼
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;
}