题目描述
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。
示例 2:
输入: “cbbd”
输出: “bb”
解题思路
- 之前面试时遇到过这个题,当时是百度的一个dp的思路,现在凭着脑海中的一点印象把代码写了出来,但是线上判题鸡很怪,我本地运行的没问题的样例,线上就给个很奇怪的结果,不懂
struct node{
string s;
int val;
};
int cmp1(struct node a,struct node b){
return a.val > b.val;
}
class Solution {
public:
string longestPalindrome(string s) {
if(s.size()<=1){
return s;
}
bool map[1005][1005];
vector<struct node> aaa;
int maxx = -9999;
for(int i=1;i<s.size();i++){
for(int j=0;j<i;j++){
if(i-j>2){
if(s[i]==s[j]&&map[j+1][i-1]==true){
map[j][i] = true;
struct node n;
n.val = i-j+1;
n.s = s.substr(j,i-j+1);
//cout<<i<<" "<<j<<" "<<n.s<<endl;
aaa.push_back(n);
}
}else if(i-j==2||i-j==1){
if(s[i]==s[j]){
map[j][i] = true;
struct node n;
n.val = i-j+1;
n.s = s.substr(j,i-j+1);
//cout<<i<<" "<<j<<" "<<n.s<<endl;
aaa.push_back(n);
}
}
}
}
if(aaa.size()==0){
return s.substr(0,1);
}
sort(aaa.begin(),aaa.end(),cmp1);
return aaa[0].s;
}
};
- 这是和之前面试时看到的差不多的思路,比我的要简介美观节省空间,而且很巧妙的记录了最长字串
- 接着仔细想了一下,这个从里往外循环,而我自己写的是从外往里,我写的是错的,这个是对的!
执行用时 :384 ms, 在所有 cpp 提交中击败了15.27%的用户
内存消耗 :186.3 MB, 在所有 cpp 提交中击败了12.16%的用户
string longestPalindrome(string s)
{
if (s.empty()) return "";
int len = s.size();
if (len == 1)return s;
int longest = 1;
int start=0;
vector<vector<int> > dp(len,vector<int>(len));
for (int i = 0; i < len; i++)
{
dp[i][i] = 1;
if(i<len-1)
{
if (s[i] == s[i + 1])
{
dp[i][i + 1] = 1;
start=i;
longest=2;
}
}
}
for (int l = 3; l <= len; l++)//子串长度
{
for (int i = 0; i+l-1 < len; i++)//枚举子串的起始点
{
int j=l+i-1;//终点
if (s[i] == s[j] && dp[i+1][j-1]==1)
{
dp[i][j] = 1;
start=i;
longest = l;
}
}
}
return s.substr(start,longest);
}
*最优解:Manacher算法
算法解释点这里
string longestPalindrome(string s)
{
int len = s.length();
if (len < 1)
{
return "";
}
// 预处理
string s1;
for (int i = 0; i < len; i++)
{
s1 += "#";
s1 += s[i];
}
s1 += "#";
len = s1.length();
int MaxRight = 0; // 当前访问到的所有回文子串,所能触及的最右一个字符的位置
int pos = 0; // MaxRight对应的回文串的对称轴所在的位置
int MaxRL = 0; // 最大回文串的回文半径
int MaxPos = 0; // MaxRL对应的回文串的对称轴所在的位置
int* RL = new int[len]; // RL[i]表示以第i个字符为对称轴的回文串的回文半径
memset(RL, 0, len * sizeof(int));
for (int i = 0; i < len; i++)
{
if (i < MaxRight)
{// 1) 当i在MaxRight的左边
RL[i] = min(RL[2 * pos - i], MaxRight - i);
}
else
{// 2) 当i在MaxRight的右边
RL[i] = 1;
}
// 尝试扩展RL[i],注意处理边界
while (i - RL[i] >= 0 // 可以把RL[i]理解为左半径,即回文串的起始位不能小于0
&& i + RL[i] < len // 同上,即回文串的结束位不能大于总长
&& s1[i - RL[i]] == s1[i + RL[i]]// 回文串特性,左右扩展,判断字符串是否相同
)
{
RL[i] += 1;
}
// 更新MaxRight, pos
if (RL[i] + i - 1 > MaxRight)
{
MaxRight = RL[i] + i - 1;
pos = i;
}
// 更新MaxRL, MaxPos
if (MaxRL <= RL[i])
{
MaxRL = RL[i];
MaxPos = i;
}
}
return s.substr((MaxPos - MaxRL + 1) / 2, MaxRL - 1);
}
/*
作者:bian-bian-xiong
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/5-zui-chang-hui-wen-zi-chuan-cc-by-bian-bian-xiong/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/