题目:
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.
题目解答:
题目要求找到一个字符串中的最长回文子串。可以知道的是,如果没碰到一个字符,就来判断它是否能够构成回文,这带来的时间花费是巨大的。因此,需要使用辅助的存储空间isPalindrome,来存储中间计算的结果,以避免过多冗余计算。
我们令i和j表示字符串s的两个位置。isPalindrome[i][j]用来记录从字符串的第i个位置到第j个位置的字符串是否为回文。
(1)若位置i的字符与位置j的字符相等,则其是否组成回文取决于[i + 1][j-1]位置是否为回文。
(2)若不等,则i到j必不组成回文。
代码如下:
class Solution {
public:
string longestPalindrome(string s) {
if(s == "")
return "";
int slen = s.length();
char strarray[slen + 1];
strncpy(strarray, s.c_str(), slen + 1);
bool isPalindrome[slen][slen];
for(int i = 0; i < slen; i++) //初始化数组
{
for(int j = 0; j < slen; j++)
{
if(j <= i) //实际上,j < i这一部分永远不会用到,姑且将他们设置成true。
{
isPalindrome[i][j] = true;
}
else
{
isPalindrome[i][j] = false;
}
}
}
//使用下面的三个变量来记录结果字符串的位置与特征
int max_sub_len = 1;
int start = 0;
int end = 0;
//迭代判断当前i到j是否为回文字符串
for(int j = 1; j < slen; j++)
{
for(int i = 0; i < j; i++)
{
if(strarray[i] == strarray[j])
{
isPalindrome[i][j] = isPalindrome[i + 1][j - 1];
if( (isPalindrome[i][j]) && (j - i + 1 > max_sub_len))
{
max_sub_len = j - i + 1;
start = i;
end = j;
}
}
else
{
isPalindrome[i][j] = false;
}
}
}
return s.substr(start, max_sub_len);
}
};