以每一个,每两个字符为中心,求出最大对称子串。返回所有子串中最长的子串, 时间复杂度O(N^2)。欢迎交流更佳算法。
class Solution {
public:
string longestPalindrome(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s.size() <= 1) return s;
int len = s.size();
int max = -1;
int mid1 = -1, mid2 = -1;
for(int i = 1; i < len; i ++)
{
int current_len = 0, start = i - 1, end = i;
while(start >= 0 && end < len && s[start] == s[end])
{
current_len += 2;
start --;
end ++ ;
}
if(current_len > max)
{
max = current_len;
mid1 = i - 1;
mid2 = i;
}
current_len = 1, start = i - 1, end = i + 1;
while(start >= 0 && end < len && s[start] == s[end])
{
current_len += 2;
start --;
end ++ ;
}
if(current_len > max)
{
max = current_len;
mid1 = i;
mid2 = -1;
}
}
int begin;
if(mid2 != -1)
{
begin = mid1 - max / 2 + 1;
}
else
{
begin = mid1 - max / 2;
}
string ans = s.substr(begin, max);
return ans;
}
};