Iterate each character as the center, expand to two ends to find the longest palindromic string.
class Solution {
public:
string longestPalindrome(string s) {
string result="";
for(int i=0;i<s.length();i++) {
string tmp=getLongest(s,i,i); // odd #
if(result.length()<tmp.length())
result=tmp;
tmp=getLongest(s,i,i+1); // even #
if(result.length()<tmp.length())
result=tmp;
}
return result;
}
string getLongest(string &s, int l, int r) {
while(l>=0 && r<s.length() && s[l]==s[r]) {
l--; r++;
}
return s.substr(l+1,r-l-1);
}
};