1 問題描述
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.
2 算法分析
最長迴文子串,這個問題之前遇到過,發現理解了之後代碼就很好寫了,基本原理就是利用了迴文串的特性:左右邊子串相同。這裏參考了Manacher算法–O(n)迴文子串算法裏面介紹的算法。
對象
- string s; //原字符串
- string s1; //用來將原字符串可能奇數或偶數個字符統一爲奇數個字符串,如abc=>#a#b#c#
- int mx; //用來表示當前掃描到的字符串迴文字符串延伸的最右端的位置
- int id; //記錄延伸到mx位置時的最中心字符位置
- int p[2005]; //輔助數組用來記錄s1[id]爲中心的迴文字符數(右半部分+中心點的個數),舉個例子:
s1: # a # b # c # b #
p:1 2 1 2 1 4 1 2 1
不同情形
根據上述描述,我們建立遍歷字符串時的情景分析,我們的任務就是把輔助數組p填滿,然後根據id,mx信息得到最長迴文串,用p[i]表示當前要填充的值。
- 情形1
此時i在當前最長迴文串的右側,因此無法利用歷史迴文的特徵來減少查找回文的過程,老老實實while循環吧
- 情形2
此時i在當前最長迴文串內部,和j關於id對稱,區域1爲j的迴文串大小(注:有可能超過id的迴文串的左邊界),如果區域1正好是如圖所示大小,則i的迴文串大小也是這麼大,否則i的迴文串在等於mx-i+1大小的基礎上繼續判斷。
3 代碼
class Solution {
public:
string longestPalindrome(string s) {
string s1;
string ans;
for (int i = 0; i < s.length(); i++)
{
s1 += "#";
s1 += s[i];
}
s1 += "#"; //#a#b#c#b#a#d#c#
int mx=0, id=0;
int p[2005];
int j,k;
for (int i = 0; i < s1.length(); i++)
{
if (i < mx){
j = 2 * id - i;
if (j - p[j] > id - p[id]) p[i] = p[j];
else {
p[i] = p[j];
while (i-p[i]>=0&&i+p[i]<s1.length()&&(s1[i+p[i]]==s1[i-p[i]]))
{
p[i]++;
}
if (p[i] > p[id]){
id = i; mx = i + p[i] - 1;
}
}
}
else{
p[i] = 1;
while (i - p[i] >= 0 && i + p[i]<s1.length() && (s1[i + p[i]] == s1[i - p[i]]))
{
p[i]++;
}
if (p[i] > p[id]){
id = i; mx = i + p[i] - 1;
}
}
}
for (int i = id - p[id] + 1; i < id + p[id]; i++)
if (s1[i] != '#')
ans += s1[i];
return ans;
}
};