Problem: 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.
Analysis: The basic idea of this problem is to check whether a sub-string to be palindromic, which is generated by one of the following two methods:
(1) Take a character from the string, and concat two substrings, one of which ends with the left character of the given one and the other starts with the right character of the given one.
(2) Find two consequent same characters. Concat two substrings, one of which ends with the left char, and the other one starts with the right one.
Take the start index and the maximal length of the substrings. The index should not be smaller than 0 and not over the length of the string.
Solutions:
(1) C++:
string longestPalindrome(string s) {
if(s.size() == 0 ||
s.size() == 1 ||
(s.size() == 2 && s[0] == s[1]))
return s;
int maxLen = 0;
int start = 0;
int size = s.size();
for(int midIndex = 1; midIndex < size - 1; ++midIndex) {
for (int i = 1; ; ++i)
if(i > midIndex ||
i >= size - midIndex ||
s[midIndex - i] != s[midIndex + i]) {
if(maxLen < 2*(i - 1) + 1) {
maxLen = 2*(i - 1) + 1;
start = midIndex - i + 1;
}
break;
}
}
for(int left = 0, right = 1; right < size; ++left, ++right) {
for (int i = 0; ; ++i)
if(i > left ||
i >= size - right ||
s[left - i] != s[right + i]) {
if(maxLen < 2*(i - 1) + 2) {
maxLen = 2*(i - 1) + 2;
start = left - i + 1;
}
break;
}
}
return s.substr(start, maxLen);
}
(2) Java:
(3) Python: