C++:
class Solution {
public:
string longestPalindrome(string s) {
int head,tail,maxLength = 0;
string * result = nullptr;
for(int i = 0; i < s.length(); ++i)
{
//子串有奇数个元素
head = i - 1;
tail = i + 1;
while(head >= 0 && tail <= s.length() - 1)
{
if(s[head] == s[tail])
{
--head;
++tail;
}
else
{
break;
}
}
if(tail - head - 1 > maxLength)
{
maxLength = tail - head - 1;
if(result != nullptr)
{
delete result;
}
result = new string(&s[head+1],&s[tail]);
}
//子串有偶数个元素
head = i;
tail = i + 1;
while(head >= 0 && tail <= s.length() - 1)
{
if(s[head] == s[tail])
{
--head;
++tail;
}
else
{
break;
}
}
if(tail - head - 1 > maxLength)
{
maxLength = tail - head - 1;
if(result != nullptr)
{
delete result;
}
result = new string(&s[head+1],&s[tail]);
}
}
return *result;
}
};
Java
思路与C++相同,速度很慢,还需优化
public String longestPalindrome(String s) {
String result = "";
int start = 0;
int end = 0;
if (s.length() != 0) {
result = s.substring(0, 1);
}
for (int i = 1; i < s.length(); ++i) {
for (int j = i - 1, k = i + 1; j >= 0 && k < s.length(); --j, ++k) {
if (s.charAt(j) == s.charAt(k)) {
start = j;
end = k;
} else {
break;
}
}
if (result.length() < end - start + 1) {
result = s.substring(start, end + 1);
}
for (int j = i - 1, k = i; j >= 0 && k < s.length(); --j, ++k) {
if (s.charAt(j) == s.charAt(k)) {
start = j;
end = k;
} else {
break;
}
}
if (result.length() < end - start + 1) {
result = s.substring(start, end + 1);
}
}
return result;
}