您的位置:首页 > 其它

[LeetCode]005-Longest Palindromic Substring

2015-12-05 19:29 351 查看
题目:

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.


Solution(1):

//这个就是暴力的方法,对每个子串进行回文判别,耗时很长,最终在LeetCode上也超时了。

string longestPalindrome(string s)
{
int max_length = 0;
string palindromic_str = "";
if(s.length() == 1)
{
return s;
}
for(int i=0;i<s.size()-1;i++)
{
for(int j =i+1;j<s.size();j++)
{
string str = s.substr(i,j-i+1);
if(IsPalindromic(str))
{
if(str.size() > max_length)
{
palindromic_str = str;
max_length = str.size();
}
}
}
}
return palindromic_str;
}

bool IsPalindromic(string str)
{
for(int i=0;i<str.size()/2;i++)
{
if(str[i] != str[str.size()-1-i])
{
return false;
}
}
return true;
}


Solution(2):

改进的算法,用Manacher算法。非常高效O(n)。

具体可看这个博客:http://blog.csdn.net/xingyeyongheng/article/details/9310555

我的代码:

string longestPalindrome(string s)
{
int n = s.size();
char * pre_induce  = new char[2*n+1];
for(int i = 0;i<n;i++)
{
pre_induce[2*i] = '#';
pre_induce[2*i+1] = s[i];
}
pre_induce[2*n] = '#';

int * p = new int[2*n+1];
memset(p,0,(2*n+1)*sizeof(int));

string str = "";
int id = 0;
int maxlen = 0;

for(int i =1;i<2*n+1;i++)
{
if(p[id] + id > i) //判断是否在范围内
{
p[i] = min(p[2*id - i],p[id]+id -i);
}
else
{
p[i] = 1;
}

while((i-p[i] >=0) && (i+p[i] <= 2*n) && (pre_induce[i+p[i]] == pre_induce[i-p[i]]))
{
++p[i];
}

if(p[i] + i > p[id] + id)
id = i;
if(maxlen < p[i])
{
maxlen = p[i]-1;
int point = (i-maxlen)/2;
str = s.substr(point,maxlen);
}
}
delete[] pre_induce;
delete[] p;
return str;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode substring