题目
关键词
回文字串
思路:
将字符串倒序,再从源字串依次比较,找到重叠位置合并
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#define MY_DEBUG printf
#define MY_DEBUG
#define MLOGI MY_DEBUG
#define MLOGE MY_DEBUG
char * shortestPalindrome(char * s)
{
if (s == NULL) {
return NULL;
}
int srcLen = strlen(s);
if (srcLen == 0) {
return s;
}
if (srcLen == 1) {
return s;
}
char *retBuf = (char *)malloc(srcLen * 2);
if (retBuf == NULL) {
return NULL;
}
int i = 0;
while(s[i] != '\0') {
retBuf[i] = s[srcLen - i - 1];
i ++;
}
for (i = 0; i < srcLen; i++) {
if (memcmp(retBuf + i, s, srcLen - i - 1) == 0) {
snprintf(retBuf + i, srcLen * 2 - i, "%s", s);
MLOGI("[%s_%d] i=%d, retBuf:%s\n", __func__, __LINE__, i, retBuf);
break;
}
}
return retBuf;
}
网友评论