Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
class Solution {
public:
string longestPalindrome(string s) {
string str;
int i = 0, j, d = 0;
if (s == "") return NULL;
if (s.length() == 1) return s;
int max = 1;
for (i = 1; i < s.length(); i++) {
d = 1;
while (i - d >= 0 && i + d < s.length() && s[i - d] == s[i + d]) {
d++;
}
if (2*d-1> max) {
max = 2 * d -1;
str = s.substr(i - d+1, max);
}
d = 0;
while (i - d -1>= 0 && i + d < s.length() && s[i - d-1] == s[i + d]) {
d++;
}
if (2 * d > max) {
max = 2 * d;
str = s.substr(i - d , max);
}
}
return str;
}
};