Description:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
Solution:
1.暴力求解
时间复杂度为O(n³)。
2.根据定义
回文串的方法就是两个两个的对称验证是否相等,那么对于找回文字串的问题,就要以每一个字符为中心,像两边扩散来寻找回文串,不过要注意奇偶情况,于回文串的长度可奇可偶两种形式的回文都要搜索。
时间复杂度为O(n²)。
3.动态规划
P(i,j)={true,false,if the substring Si…Sj is a palindromeotherwise.
Therefore,
P(i,j)=(P(i+1,j−1) and Si==Sj)
The base cases are:
P(i,i)=true
P(i,i+1)=(Si==Si+1)
时间复杂度O(n²)。
3.Manacher算法
马拉车算法,十分巧妙的把时间复杂度变为线性。即时间复杂度为O(n)。
参考:http://blog.csdn.net/dyx404514/article/details/42061017
代码:
class Solution {//19ms
public:
string longestPalindrome(string s) {
int length = s.size();
int start = 0, end = 0;
if (length == 0) return s;
for (int i = 0; i < length; i++) {
searchPalindrome(s, i, i, start, end);
searchPalindrome(s, i, i+1, start, end);
}
return s.substr(start,end-start+1);
}
void searchPalindrome(string s, int i, int j, int &start, int &end) {
int length = s.size();
while (i >= 0 && j < length && s[i] == s[j])
i--, j++;
i++,j--;
if (j - i > end - start) {
start = i;
end = j;
}
}
};
class Solution {//102ms
public:
string longestPalindrome(string s) {
int dp[s.size()][s.size()] = {0}, left = 0, right = 0, len = 0;
for (int i = 0; i < s.size(); ++i) {
for (int j = 0; j < i; ++j) {
dp[j][i] = (s[i] == s[j] && (i - j < 2 || dp[j + 1][i - 1]));
if (dp[j][i] && len < i - j + 1) {
len = i - j + 1;
left = j;
right = i;
}
}
dp[i][i] = 1;
}
return s.substr(left, right - left + 1);
}
};
class Solution {//3ms
public:
string longestPalindrome(string s) {
string t ="$#";
for (int i = 0; i < s.size(); ++i) {
t += s[i];
t += '#';
}
int p[t.size()] = {0}, id = 0, mx = 0, resId = 0, resMx = 0;
for (int i = 0; i < t.size(); ++i) {
p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
while (t[i + p[i]] == t[i - p[i]]) ++p[i];
if (mx < i + p[i]) {
mx = i + p[i];
id = i;
}
if (resMx < p[i]) {
resMx = p[i];
resId = i;
}
}
return s.substr((resId - resMx) / 2, resMx - 1);
}
};