最长回文子串-C
题目描述 : ------------------------------------------------------------
对于一个字符串,请设计一个高效算法,计算其中最长回文子串的长度。
输入样例 : ------------------------------------------------------------
“abc1234321ab”,12
返回值 : ------------------------------------------------------------
7
class Solution {
public:
int getLongestPalindrome(string A, int n) {
vector<vector<bool>> dp(n, vector<bool>(n));
int maxLen = 1;
if (n <= 1)
return n;
for (int i = 0; i < n; i++)
for (int j = 0; j + i < n; j++) {
if (i == 0)
dp[j][j] = 1;
else if (i == 1)
dp[j][j + 1] = A[j] == A[j + 1];
else if (A[j] == A[j + i])
dp[j][j + i] = dp[j + 1][j + i - 1];
if (dp[j][j + i])
maxLen = max(maxLen, i + 1);
}
return maxLen;
}
};
class Solution {
public:
int getLongestPalindrome(string A, int n) {
if (n <= 1)
return n;
int left = 0, right = 0, maxLen = 1;
for (int i = 0; i < n; i++) {
left = right = i;
while (left >= 0 && right < n && A[left] == A[right]) {
left--;
right++;
}
maxLen = max(maxLen, right - left - 1);
left = i;
right = i + 1;
while (left >= 0 && right < n && A[left] == A[right]) {
left--;
right++;
}
maxLen = max(maxLen, right - left - 1);
}
return maxLen;
}
};
class Solution {
public:
int getLongestPalindrome(string A, int n) {
if(n <= 1)
return n;
A.insert(A.begin(), '#');
for(int i = 1; i <= n; i++)
A.insert(A.begin() + 2 * i, '#');
n = 2 * n + 1;
int longest = 1;
vector<int> armLen(n);
for(int i = 0; i < n; i++)
armLen[i] = 1;
int pos = -1, maxDis = -1;
int left, right;
for(int i = 0; i < n; i++) {
if(maxDis > i) {
if(armLen[2 * pos - i] + i - 1 <= maxDis)
armLen[i] = armLen[2 * pos - i];
else
armLen[i] = maxDis - i + 1;
}
left = i - armLen[i], right = i + armLen[i];
while(left >= 0 && right < n) {
if(A[left--] == A[right++])
armLen[i]++;
else break;
}
longest = max(longest, armLen[i] - 1);
if(armLen[i] + i - 1 > maxDis) {
maxDis = armLen[i] + i - 1;
pos = i;
}
}
return longest;
}
};