下面是一個使用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
函數來查找最長的回文子串并輸出結果。