最长回文子串问题求解
今天看到的一个题目,希望大家能提供点思路。。。。。输入一个字符串,求出其中最长的回文子串。子串的含义是:在原串连续出现的字符串片段。回文的含义是:正着看和倒着看是相同的,如abba和abbebba。在判断是要求忽略所有的标点和空格,且忽略大小写,但输出时按原样输出(首尾不要输出多余的字符串)。输入字符串长度大于等于1小于等于5000
样例输入
She say:Madam,I'm Adam.
样例输出
Madam,I'm Adam
#include <stdio.h> #include <string.h> #define MAX 5000 typedef struct Data { int len; char *p; }Data; Data result = {1, NULL}; int isletter(char ch) { if ('a' <= ch && 'z' >= ch) return 1; if ('A' <= ch && 'Z' >= ch) return 1; return 0; } int issame(char a, char b) { if (a == b) return 1; if (a > b) a -= 'a' - 'A'; else a += 'a' - 'A'; return a == b; } void Judge(char *str, int n) { if (!isletter(*str))return; int temp = 1, len = n; char *p, *q; p = str-1, q = str+1; while (len > 0 && *q) { while (!isletter(*p)&& len--)p--; if (!len) break; while (!isletter(*q)&& *(q++)); if (!*q) break; if (!issame(*p, *q))break; temp += 2, p--, q++; } if (result.len < temp) { while (!isletter(*(++p))); result.len = temp, result.p = p; } p = str, q = str+1, temp = 0, len = n; while (len > 0 && *q) { while (!isletter(*p)&& len--)p--; if (!len) break; while (!isletter(*q)&& *(q++)); if (!*q) break; if (!issame(*p, *q))break; temp += 2, p--, q++; } if (result.len < temp) { while (!isletter(*(++p))); result.len = temp, result.p = p; } } void Output() { while (result.len) { printf("%c", *(result.p)); result.len -= isletter(*(result.p++)); } puts(""); } int main() { char str[MAX]; gets(str); int len = strlen(str); for (int i = 1;i < len-result.len;) Judge(&str[i], i), i++; Output(); return 0; }