最长回文子串 c语言
时间: 2023-12-07 09:40:06 浏览: 109
以下是C语言实现最长回文子串的例子:
```c
#include <stdio.h>
#include <string.h>
char* longestPalindrome(char* s) {
int len = strlen(s);
if (len < 2) {
return s;
}
int maxLen = 1;
int begin = 0;
int dp[len][len];
memset(dp, 0, sizeof(dp));
for (int i = 0; i < len; i++) {
dp[i][i] =1;
}
for (int L = 2; L <= len; L++) {
for (int i = 0; i < len; i++) {
int j = i + L - 1;
if (j >= len) {
break;
}
if (s[i] != s[j]) {
dp[i][j] = 0;
} else {
if (j - i < 3) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i + 1][j - 1];
}
}
if (dp[i][j] && j - i + 1 > maxLen) {
maxLen = j - i + 1;
begin = i;
}
}
}
s[maxLen + begin] = '\0';
return s + begin;
}
int main() {
char s[] = "babad";
printf("%s\n", longestPalindrome(s)); // 输出:bab
return 0;
}
```
阅读全文