下面是一個(gè)使用C語(yǔ)言實(shí)現(xiàn)查找最長(zhǎng)回文子串的例子:
#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;
}
在上面的代碼中,我們定義了一個(gè)expandAroundCenter
函數(shù)來(lái)查找以某個(gè)中心展開的回文子串的長(zhǎng)度。然后我們遍歷字符串s
,以每個(gè)字符為中心向兩邊擴(kuò)展,分別計(jì)算出奇數(shù)長(zhǎng)度和偶數(shù)長(zhǎng)度的回文子串的長(zhǎng)度,找出最長(zhǎng)的回文子串并返回。最后在main
函數(shù)中調(diào)用longestPalindrome
函數(shù)來(lái)查找最長(zhǎng)的回文子串并輸出結(jié)果。