输入一个字符串,求出其中最长的回文子串。回文子串的含义是:正着看和倒着看是相同的,如abba和abbebba。
在这里我们采用的方法:
第一步,倒转原子串;
第二步,求两个串的最长公共子串;
第三步,判断该子串是不是回文串。
代码如下:
#include iostream
#include string
using namespace std;
string longestPalSubstr(const string &str)
{
int len = str.length();
if (len < 2) return str;
string tep;
//求原字符串的倒置str1
string str1 = str;
int i = 0, j = len - 1;
while (i < j)
{
char temp = str1[i];
str1[i] = str1[j];
str1[j] = temp;
i++; j--;
}
//求两个字符串的最长公共子串
for (i = len; i > 1; i--)
{
for (j = 0; j + i <= len; j++)
{
tep = str.substr(j, i);
int t = str1.rfind(tep);
//判断该字符串是不是回文串
if ( t != -1 && j + t + i == len)
return tep;
}
}
return str.substr(0, 1);
}
int main()
{
string str;
for (int i = 0; i < 5; i++)
{
cout << "请输入一个字符串:";
cin >> str;
string substr = longestPalSubstr(str);
cout << " 最长回文子串是:" << substr << endl << endl;
}
system("PAUSE");
return 0;
}
以下是求回文子川数
#include<bits/stdc++.h>
using namespace std;
#define max(a,b) a>b?a:b
int calc_result(int block, int *p,int len)
{
unsigned __int64 result_mid=1;
unsigned __int64 result_mid_big=1;
for (int i = 1; i <= block; i++)
{
int sum=0;
result_mid_big=result_mid_big*i;
for (int j = 2; j <= len; j++)
{
sum+=*(p+j);
if (*(p+j)==0)
{
continue;
}
if (result_mid_big%j==0)
{
result_mid_big=result_mid_big/j;
(*(p+j))--;
}
}
if (sum==0)
{
if (result_mid_big>1000000007)
{
result_mid_big=result_mid_big%1000000007;
}
}
}
return (int)result_mid_big;
}
int palindrome(const char *s)
{
int len = strlen(s);
if (len > 100)
{
printf("Strings too long");
return 0;
}
int num[26]={0};
int flag_len = len % 2;
int flag_bit,flag=0;
int num_bit[26]={0};
int MAX=0;
for (int i = 0; i < len; i++)
{
num[*(s+i)-'a']++; //统计出每个字母出现的个数
}
for (int i = 0; i < 26; i++)
{
flag_bit = num[i] % 2;
if (flag_bit==1)
{
flag++;
}
if ((flag_len == 0 && flag_bit == 1) || (flag_len == 1 && flag > 1)) //字符串长度为偶数,但是有出现基数词的字符,则不可能是回文字符
{
return 0;
}
num_bit[i] = num[i]/2;
MAX = max(MAX,num_bit[i]);
}
int *p_num = new int[MAX+1]();
for (int i = 0; i < 26; i++)
{
if (num_bit[i]<=1)
{
continue;
}
for (int j = 2; j <= num_bit[i]; j++)
{
(*(p_num+j))++;
}
}
int block = len/2;
int result=calc_result(block,p_num,MAX);
printf("Result is %d \n",result);
delete[] p_num;
return result;
}
int main()
{
char str[101];
while(scanf("%s",str)){
palindrome(str);
}
return 0;
}