题目
很明显暴力方法是n平方复杂度,所以一直在想有没有不是n平方复杂度的方法。然后就掉坑里了。
最后看了题解发现其实就是n平方复杂度,所以就直接暴力了。
附上一份随手暴力代码,遍历对称中心。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
if (s.size()==1)
{
return s;
}
int maxL = 1;
int maxIndex = 0;
for(int i = 0;i<=(s.size()-1)*2;i++)
{
int len ;
int l ;
int r ;
if(i%2 == 0)
{
len = 1;
l = i/2-1;
r = i/2 +1;
while (l>=0 && r <s.size())
{
if( s[l] == s[r] )
{
len += 2;
}
else
{
break;
}
l--;
r++;
}
}
else
{
len = 0;
l = (i-1)/2;
r = (i+1)/2;
while (l>=0 && r <s.size())
{
if( s[l] == s[r] )
{
len += 2;
}
else
{
break;
}
l--;
r++;
}
}
if (len > maxL)
{
maxL = len;
maxIndex = l+1;
}
}
return s.substr(maxIndex,maxL);
}
};
int main()
{
Solution solution;
cout<<solution.longestPalindrome("aacabdkacaa")<<endl;;
}