下面是一个使用C语言实现查找最长回文子串的例子:
#include <stdio.h>
#include <string.h>
int expandAroundCenter(char *s, int left, int right) {
int len = strlen(s);
while (left >= 0 && right < len && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
char *longestPalindrome(char *s) {
if (s == NULL || strlen(s) < 1) {
return "";
}
int start = 0, end = 0;
for (int i = 0; i < strlen(s); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = len1 > len2 ? len1 : len2;
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
char *result = (char *)malloc((end - start + 2) * sizeof(char));
strncpy(result, s + start, end - start + 1);
result[end - start + 1] = '\0';
return result;
}
int main() {
char *s = "babad";
char *result = longestPalindrome(s);
printf("Longest Palindromic Substring: %s\n", result);
free(result);
return 0;
}
在上面的代码中,我们定义了一个expandAroundCenter
函数来查找以某个中心展开的回文子串的长度。然后我们遍历字符串s
,以每个字符为中心向两边扩展,分别计算出奇数长度和偶数长度的回文子串的长度,找出最长的回文子串并返回。最后在main
函数中调用longestPalindrome
函数来查找最长的回文子串并输出结果。