题目链接:https://leetcode.com/problems/longest-palindromic-substring/
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
思路
中心法求回文数
要求一个字符串的最大回文数,最暴力的方法是穷举所有可能,即枚举[1,len]长度的子串,判断是否回文。这种时间复杂度太高。使用中心法求回文数的思路是借助两个指针,以一个字符为中心,或者以两个字符之间为中心向左右扫描,判断是否相等,如此即可将时间复杂度降为O(n^2)
class Solution {
public:
string longestPalindrome(string s) {
if(s.size() == 0) return "";
int len = s.size(),Max = 0;
string ans;
for(int i = 0;i < 2*len -1;i++){
int left = i/2,right = (i+1)/2;
while(left >= 0 && right < len && s[left] == s[right])
left--,right++;
if(Max <= right-left-1){
Max = right - left -1;
ans = s.substr(left+1,Max);
}
}
return ans;
}
};