想了一晚上,觉得 这基本上是最优解法了。。
string palindromic(string s) {
int i, i2, j, n = s.length(), tmp;
if (n < 2 || (n == 2 && s[0] == s[1]))
{
return s;
}
int max = 0, start = 0;
for (i = 0; i < n - 1; i++)
{
i2 = i;
while (s[i2] == s[i2 + 1])
{
i2++;
}
tmp = (max - i2 + i)/2;
if (i2 + tmp >= n || i - tmp < 0 || s[i2 + tmp] != s[i-tmp])
{
i = i2; continue;
}
for (j = 1;; j++)
{
if (i < j || i2 + j > n - 1 || s[i - j] != s[i2 + j])
{
break;
}
}
if (2 * (j - 1) + i2 - i > max)
{
max = 2 * (j - 1) + i2 - i;
start = i - j + 1;
}
i = i2;
}
return s.substr(start, max + 1);
}