这个题目有很多经典解法,嘴笨的就是N的三次方的解法,这里就不说了,下面是n的平方的解法,是从中间向两边查找的解法。
class Solution {
public:
string longestPalindrome(string s) {
int n = s.length();
if (n == 0) return "";
string longest = s.substr(0, 1);
for (int i = 0; i < n-1; i++) {
string p1 = expandAroundCenter(s, i, i);
if (p1.length() > longest.length())
longest = p1;
string p2 = expandAroundCenter(s, i, i+1);
if (p2.length() > longest.length())
longest = p2;
}
return longest;
}
string expandAroundCenter(string s, int c1, int c2) {
int l = c1, r = c2;
int n = s.length();
while (l >= 0 && r <= n-1 && s[l] == s[r]) {
l--;
r++;
}
return s.substr(l+1, r-l-1);
}
};