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.
先给个暴力解法, O(N3)...答案说有O(N)的解法。。。临时想不出。。。明天再想想
class Solution {
public:
string longestPalindrome(string s) {
int n=s.size();
if (n<=1)
return s;
int length=1;
int mybgn;
for (int bgn=0; bgn<n; bgn++){
for (int end=bgn+length-1; end<n;end++) {
if (isPalindrome(s,bgn,end) && end-bgn+1>length)
{
mybgn=bgn;
length=end-bgn+1;
}
}
}
return string(s,mybgn,length);
}
bool isPalindrome(string s, int bgn, int end)
{
int n=s.size();
while(s[bgn]==s[end] && end>=0 && bgn <n )
{
bgn++;
end--;
}
return bgn>=end;
}
};
看了下答案,写了下dp...用矩阵对角性质解问题,好新颖啊。。。。
class Solution {
public:
string longestPalindrome(string s) {
bool tbl[1000][1000]={false};
int len=1;
int bgn=0;
int n=s.size();
for (int i=0; i<n;i++)
tbl[i][i]=true;
for (int i=0; i<n-1;i++)
{
if (s[i]==s[i+1])
{
tbl[i][i+1]=true;
bgn=i;
len=2;
}
}
for (int length=3; length<=n; length++)
for (int i=0; i<n-length+1; i++)
{
int j=i+length-1;
if (s[i]==s[j] && tbl[i+1][j-1])
{
tbl[i][j]=true;
len=length;
bgn=i;
}
}
return s.substr(bgn,len);
}
};