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.
Example
思路是找中间那个数,或者中间那两个数, 然后从两边开始往外扩展。
Given the string = "abcdzdcab"
, return "cdzdc"
.
class Solution {
public:
/**
* @param s input string
* @return the longest palindromic substring
*/
string longestPalindrome(string& s) {
// Write your code here
string longest_str = "";
if (s.size() == 0) {
return longest_str;
}
for (int i = 0 ; i < s.size(); i++) {
int l = i;
int r = i;
while (i >= 0 && r < s.size() && s[l] == s[r]) {
if ( r - l + 1 > longest_str.size()) {
longest_str = s.substr(l, r - l + 1);
}
l--;
r++;
}
l = i;
r = i + 1;
while (i >= 0 && r < s.size() && s[l] == s[r]) {
if ( r - l + 1 > longest_str.size()) {
longest_str = s.substr(l, r - l + 1);
}
l--;
r++;
}
}
return longest_str;
}
};