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.
使用双指针
public class Solution
{
public string LongestPalindrome(string s)
{
int n = s.Length;
if (n < 2)
return s;
string res = Fun(s,1, "");
if (n < 3)
return res;
return Fun(s,2, res);
}
private string Fun(string s,int offset,string res)
{
int tmp,p1 =0, p2 = offset;
while (p2 < s.Length)
{
if (s[p1] == s[p2])
{
tmp = p1 + 1;
while (p1 >= 0 && p2 < s.Length && s[p1] == s[p2])
{
p1--;
p2++;
}
if (p2 - p1 - 1 > res.Length)
{
res = s.Substring(p1 + 1, p2 - p1 - 1);
}
p1 = tmp;
p2 = p1 + offset;
}
else
{
p1++;
p2++;
}
}
return res;
}
}
动态规划(并不能提高算法效率)
public string LongestPalindrome(string s)
{
int n = s.Length;
if (n < 2)
return s;
string res = "";
bool[,] b = new bool[n,n];
int max = 0;
for (int i= n-1; i >=0; i--)
{
for (int j = i; j < n; j++)
{
if (s[i] == s[j] && (j - i < 3 || b[i+1,j - 1]))
{
b[i,j] = true;
if (j - i + 1 > max)
{
max = j - i + 1;
res = s.Substring(i, max);
}
}
}
}
return res;
}
参考:
http://blog.csdn.net/linhuanmars/article/details/20888595
Manacher’s Algorithm的算法
public string LongestPalindrome(string s)
{
int n = s.Length;
if (n < 2)
return s;
string t = "^";
for (int i = 0; i < n; i++)
{
t += "#" + s[i];
}
t += "#$";
n = t.Length;
int[] p = new int[n];
int c = 0, r = 0, max = 0, index = 0;
for (int i = 1; i < n - 1; i++)
{
p[i] = r > i ? Math.Min(r - i, p[2 * c - i]) : 0;
while (t[i + 1 + p[i]] == t[i - 1 - p[i]])
p[i]++;
if (i+p[i] > r)
{
c = i;
r = i + p[i];
}
if (p[i] > max)
{
max = p[i];
index = i;
}
}
return s.Substring((index - 1 - max) / 2, max);
}
参考 http://blog.csdn.net/hopeztm/article/details/7932245