C++
1. 中心扩展算法
要始终记住索引要比真实长度少一,所以要表示真实长度要加一
R-L-1那里是因为当回文时就r++l–,所以r和l最后指的位置时回文子串的前一和后一的位置,算出的真实长度(R-L+1)要减2
class Solution {
public:
string longestPalindrome(string s)
{
if (s.length() < 1)
{
return "";
}
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++)
{
int len1 = expandAroundCenter(s, i, i); //一个元素为中心
int len2 = expandAroundCenter(s, i, i + 1); //两个元素为中心
int len = max(len1, len2);
if (len > end - start)
{
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substr(start, end - start + 1);
}
int expandAroundCenter(string s, int left, int right)
{
int L = left, R = right;
while (L >= 0 && R < s.length() && s[L] == s[R])
{// 计算以left和right为中心的回文串长度
L--;
R++;
}
return R - L - 1; //当回文时就r++l--所以r和l最后指的位置时回文子串的前一和后一的位置
}
};
Python
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ''
for i in range(len(s)):
s1 = self.find(s, i, i) # 以当前字符为中心的最长回文子串
s2 = self.find(s, i, i+1) # 以当前字符和下一字符为中心的最长回文子串
#如果最大长度有变化则更新res
if max(len(s1), len(s2)) > len(res):
res = s2 if len(s1) < len(s2) else s1
return res
def find(self, s, left, right):
#找到当前中心的最大长度子串
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right] #切片到right的前一个,不包括right