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.
解题方法1.
简单搜索+适当的判断退出机制
从string第一个character开始,从string结尾往前找到同样的character,判断其是否为回文,并找出最大的。
tips:有几个退出点可以减少程序运行时间,其一是从后往回找时,如果substring的长度已经小于当前最长的回文长度,则终止while。其二是要随时满足剩下可能出现的最长的回文字符串要长于已找到的回文字符串长度,否则退出。
解题方法2.(重点)
动态规划,用到辅助数组arr[i,j] == 1 if 从i到j范围内的substring是回文,否则为0.
通过观察发现有以下几条规律
1.arr[i,j] = 1 if i == j
2.arr[i,j] = 1 if j == i + 1 && s[i] == s[j]
3.arr[i,j] = 1 if j == i + 2 && s[i] == s[j]
4.arr[i,j] = 1 if j == i + 3 && s[i] == s[j] && arr[i+1, j-1]
........
所以又回到动态规划的思想上。
实际效果方法2比方法1在时间复杂度上要好很多,但是空间开销大,对于N = 1000, 要生成1000*1000的数组。
string longestPalindrome(string s) {
int currentmax = 0;
string currentstr;
int begin, end;
int i = 0;
while(s.size() - i - 1 > currentmax ){
unsigned found = s.rfind(s[i]);
while(true){
if(found == string::npos)break;
string sub = s.substr(i,found - i + 1);
if(sub.size() < currentmax)break;
if(ispalindromic(sub)){
if(sub.size() > currentmax){
begin = i;
end = i + sub.size() - 1;
currentmax = sub.size();
currentstr = sub;
}
break;
}
found = s.rfind(s[i],found-1);
}
++i;
}
cout<<s.size()<<endl;
return currentstr;
}
string longestPalindromeDP(const string &s){
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
arr[i][j] = 0;
int maxlength = 0;
int start = 0;
int end = 0;
for(int i = 0; i < s.size(); ++i){
for(int j = 0; j < i; ++j){
arr[j][i] = (s[i] == s[j] && (i <= j + 1 || arr[j+1][i-1]));
if(arr[j][i] == 1 && maxlength < i - j + 1){
maxlength = i - j + 1;
start = j;
end = i;
}
}
arr[i][i] = 1;
}
return s.substr(start,maxlength);
}