C语言最长回文字符串
时间: 2024-08-15 22:03:27 浏览: 72
在C语言中,寻找一个字符串中最长的回文子串是一个经典的算法问题。这里有一个常见的解决方案,基于中心扩散法(Manacher's Algorithm),它的时间复杂度是O(n)。
首先,你需要包含头文件并定义一些辅助变量:
```c
#include <stdio.h>
#include <string.h>
int max_length;
int center; // 当前回文半径的最大值
int end; // 最右边界的位置
// 函数用于查找最长回文子串
void findLongestPalindrome(char* str) {
int len = strlen(str);
if(len == 0)
return;
for(int i = 0; i < len; ++i) {
int left = (center - i > 0) ? center - i : 0;
int right = (center + i < len - 1) ? center + i : len - 1;
while(left >= 0 && right < len && str[left] == str[right]) {
if(right - left + 1 > max_length) {
max_length = right - left + 1;
end = i;
}
left--;
right++;
}
}
}
int main() {
char str[100];
printf("请输入一个字符串: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // 清理换行符
findLongestPalindrome(str);
printf("最长回文子串长度为 %d, 子串是: ", max_length);
for(int i = end - max_length + 1; i <= end; i++)
printf("%c", str[i]);
printf("\n");
return 0;
}
```
当你运行这个程序,它将接收用户输入的字符串,然后找出其中最长的回文子串。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![php](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)