最长回文子串问题是一个经典问题,成熟的算法有很多,这篇博客采用的方案是基于Longest common substring的,关于Longest common substring可参考 这里。
代码也是参照上篇博客修改的
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int longestPalindrome(string s, vector<string>& MaxSubstr) {
string s_reverse= s;
int i, j, k = 0, len = s.length(), MaxSubstrLen = 0;
for (i = 0; i < len; i++)
{
s_reverse[i] = s[len - 1 - i];
}
vector<vector<int>> L(len, vector<int>(len, 0)); // L记录相同子串的长度
//vector<string> MaxSubstr(len);
for (i = 0; i < len; i++)
{
for (j = 0; j < len; j++)
{
if (s[i] == s_reverse[j])
{
if (i == 0 || j == 0)
L[i][j] = 1;
else
L[i][j] = L[i - 1][j - 1] + 1;
if (MaxSubstrLen < L[i][j] && i + 1 - L[i][j] == len - 1 - j) //当得到的公共子串substr在s中的位置与substr的reverse对应在s中的位置相等时,则是公共回文串
{
MaxSubstrLen = L[i][j];
k = 0;
MaxSubstr[k] = s.substr(i + 1 - MaxSubstrLen, MaxSubstrLen);
}
else if (MaxSubstrLen == L[i][j] && MaxSubstr[k] != s.substr(i + 1 - MaxSubstrLen, MaxSubstrLen))
//有多个长度相同的MaxSubstr, 且要排除多个MaxSubstr内容相同的情况,如当str1="a", str2="aaaa"
MaxSubstr[++k] = s.substr(i + 1 - MaxSubstrLen, MaxSubstrLen);
}
else
L[i][j] = 0;
}
}
return k;
}
};
int main()
{
string s = "abcdsabc";
vector<string> MaxSubstr(s.length());
Solution a;
int MaxSubstrNum =a.longestPalindrome(s, MaxSubstr);
for (int i = 0; i <= MaxSubstrNum; i++)
cout << MaxSubstr[i] << ' ';
cout << endl;
return 0;
}