# Leetcode 5. Longest Palindromic Substring 题解

Last Updated At: 2016-03-31

## 我的解

84ms

class Solution {
public:
std::string longestPalindrome(std::string s) {
if (s.size()==0)
return s;
size_t max_len = 0;
std::pair<size_t, size_t> res_ij;
for (size_t i = 0; i < s.size(); ++i)
{
// odd case
for (size_t j = 1; j <= i && i + j < s.size(); ++j)
{
if (s[i - j] == s[i + j])
{
if (2 * j + 1 > max_len)
{
max_len = 2 * j + 1;
res_ij = std::make_pair(i, j);
}
}
else
{
break;
}
}

// even case
for (size_t j = 1; j <= i && i + j -1 < s.size(); ++j)
{
if (s[i - j] == s[i + j -1])
{
if (2 * j > max_len)
{
max_len = 2 * j;
res_ij = std::make_pair(i, j);
}
}
else
{
break;
}
}
}
return max_len != 0 ? s.substr(res_ij.first - res_ij.second, max_len):s.substr(0, 1);
}
};


## 启发

This algorithm is definitely non-trivial and you won’t be expected to come up with such algorithm during an interview setting. However, I do hope that you enjoy reading this article and hopefully it helps you in understanding this interesting algorithm. You deserve a pat if you have gone this far! :)

♥ It's Easy if You Try