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.
[Solution]
说明:版权所有,转载请注明出处。 Coder007的博客class Solution {
public:
/**
* return the longest palindrome between s1[n:1] and s2[1:m]
* Example: s1=asdf, s2=fdsb, return sdffds
* odd=true
* s1[n] is the center of the result(the length of the result is odd)
* odd=false
* s1[n]s2[1] is the center of the result(the length of the result is even)
*/
string palindrome(string s1, string s2, bool odd){
// s1 is empty
if(s1.size() == 0)return "";
// s1 is not empty, s2 is empty
if(s2.size() == 0){
// the length of the result is odd
if(odd){
return s1.substr(s1.size()-1, 1);
}
// the length of the result is even
else{
return "";
}
}
// both s1 and s2 are not empty
if(odd){
int i = s1.size()-2, j = 0, len = 0;
while(i >= 0 && j <= s2.size()-1 && s1[i] == s2[j]){
i--;
j++;
len++;
}
return s1.substr(s1.size()-1-len, len+1) + s2.substr(0, len);
}
else{
int i = s1.size()-1, j = 0, len = 0;
while(i >= 0 && j <= s2.size()-1 && s1[i] == s2[j]){
i--;
j++;
len++;
}
return s1.substr(s1.size()-len, len) + s2.substr(0, len);
}
}
/**
* get the longest palindrome substr in s
*/
string longestPalindrome(string s){
// Start typing your C/C++ solution below
// DO NOT write int main() function
string res = "";
for(int i = 0; i <= s.size(); ++i){
string s1 = s.substr(0, i);
string s2 = s.substr(i, s.size() - i);
// get longest palindrome in two ways
string odd = palindrome(s1, s2, true);
string even = palindrome(s1, s2, false);
// update result
res = odd.size() > res.size() ? odd : res;
res = even.size() > res.size() ? even : res;
}
return res;
}
};