题目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
思路:遍历字符串,计算以当前字符为“中心”的最长对偶串。算法复杂度O(n^2)。
针对此问题有专门的算法-manacher算法,可以实现O(n)复杂度,但是思路还未搞透彻。
代码:
class Solution {
public:
string longestPalindrome(string s) {
// O(n^2) 顺序遍历s,以遍历字符为中心双向增长。
string res;
for(int i = 0; i < s.size(); i++){
string temp1,temp2;
temp1= getPalString(s,i,i); // 考虑奇数情况 'aba'
if(temp1.size() > res.size()) res = temp1;
temp2 = getPalString(s,i,i+1); // 偶数情况 'abba'
if(temp2.size() > res.size()) res = temp2;
}
return res;
}
// 函数计算以l,r展开得到的最长对偶串
string getPalString(string s, int l, int r){
while(l>=0 && r<s.size() && s[l] == s[r]){
l--; r++;
}
return s.substr(l+1,r-1-l); // 返回对偶子串
}
};
python