此方法是动态规划。时间复杂度为O(n^2)。线性时间可以学习Manacher算法
#include <bits/stdc++.h>
using namespace std;
int lpsubstring(char *str,int n)
{
bool table[n][n];//记录某索引到某索引是不是回文子串
memset(table, 0, sizeof(table));//初始化table
/*
当最长子串的长度是一时,每个字符都是回文,则table值为true
*/
int max_len = 1;
for(int i = 0; i < n; i++)
table[i][i] = true;
//查找字符串中长度为二的回文子串,start记录回文子串的起始索引
int start = 0;
for(int i = 0; i < n-1; i++)
{
if(str[i] == str[i+1])
{
table[i][i+1] = true;
start = i;
max_len = 2;
}
}
//查找字符串中回文子串的长度大于二的子串
for(int k = 3; k <= n; k++)
{
for(int i = 0; i+k <= n; i++)
{
int j = i+k-1;
//为了计算table[i][j] 我们先table[i+1][j-1]是否为true
if(table[i+1][j-1] && str[i] == str[j])
{
table[i][j] = true;
if(k > max_len)
{
start = i;//记录索引
max_len = k;//记录最大长度
}
}
}
}
//打印回文子串
for(int i = start; i < start+max_len; i++)
cout << str[i];
cout << endl;
return max_len;
}
int main(void)
{
char str[] = "agsasccsasqwf";
int n = strlen(str);
cout << lpsubstring(str,n);
return 0;
}