100ms,超29%。。。
class Solution {
public:
string longestPalindrome(string s) {
int Aindex = 0, Alen = 0;
int Bindex = 0, Blen = 0;
string stra,strb;
auto len = s.size();
if(len == 1)
return s;
if(len == 2)
{
if(s[0] == s[1])
return s;
else
{
stra.push_back(s[0]);
return stra;
}
}
for(int i=1; i<s.size(); i++)
{
stra = "";
stra.push_back(s[i]);
strb = "";
int j =1;
while(j<=i && j<(len-i) && (s[i-j]==s[i+j])) //以某个数为中心奇对称,或某个数及右侧数一起偶对称
{
// int LenA = 0;
stra.insert(0,1,s[i-j]);
stra.push_back(s[i+j]);
auto LenA = stra.size();
if(LenA > Alen)
{
Alen = LenA;
Aindex = i;
}
j++;
}
j = 0;
while(j<=(i-1) && j<(len-i) && s[i-j-1]==s[i+j]) //偶对称
{
strb.insert(0,1,s[i-j-1]);
strb.push_back(s[i+j]);
auto LenB = strb.size();
if(LenB > Blen)
{
Blen = LenB;
Bindex = i;
}
j++;
}
}
if(Alen == 0 && Blen ==0)
{
string cc;
cc.push_back(s[0]);
return cc;
}
if(Alen>Blen ||(Alen== Blen&& Aindex < Bindex))
{
return s.substr(Aindex-Alen/2,Alen);
}else
{
return s.substr(Bindex-Blen/2, Blen);
}
}
};
阅读了别人的思路,改进了自己的算法,16ms,超过62%.
In fact, we could solve it in O(n2)O(n^2)O(n2) time using only constant space.
We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n−12n - 12n−1 such centers.
You might be asking why there are 2n−12n - 12n−1 but not nnn centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as "abba") and its center are between the two 'b's.
其实思路跟自己的差不多,但细节处理没别人做得好。
class Solution {
private:
int expandAroundCenter(string s, int left, int right)
{
int L = left, R = right;
while(L>=0 && R <s.size() && s[L] == s[R])
{
L--;
R++;
}
return R-L-1; //最后L--和R++抵消掉
}
public:
string longestPalindrome(string s)
{
if(s=="" || s.size()<1)
return "";
int start = 0 , end = 0;
for(int i=0; i<s.size(); i++)
{
int len1 = expandAroundCenter(s,i,i);
int len2 = expandAroundCenter(s,i,i+1);
int len = len1>len2? len1:len2;
if(len > end - start)
{
start = i - (len-1)/2;
end = i + len/2;
}
}
return s.substr(start,end-start+1);
}
};