版权声明:转载请注明出处 https://blog.csdn.net/FGY_u/article/details/84315909
题目: https://leetcode.com/problems/longest-palindromic-substring/
概述: 求长回文串
思路: 一个for循环,i为下标,我们以这个i为中心,向两边辐射,看最长的回文串能有多长。记住要考虑两种情况:①要求的最长回文串为偶数个 ②要求的回文串为奇数个。 这点会在传参中体现。
class Solution {
public:
int lo, max_len = 0;
string longestPalindrome(string s) {
int len = s.size();
if(len < 2) return s;
for(int i = 0; i < s.size() - 1; i++)
{
checkPalindrome(s, i, i);
checkPalindrome(s, i, i + 1);
}
return s.substr(lo, max_len);
}
void checkPalindrome(string s, int i, int j)
{
while(i >= 0 && j < s.size() && s[i] == s[j])
{
i--;
j++;
}
if(max_len <= j - i - 1)
{
lo = i + 1;
max_len = j - i - 1;
}
}
};