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.
题意:
给定一个字符串s,找到s中最长的回文子串
假定s的最大长度是1000,存在第一个唯一的最长的回文字串。
/*
边界条件是len=1和len=2的情况。
状态转移条件。
初始状态
f(i,i)=1 f(i,i+1)=2
P[i,j] = (P[i + 1, j - 1] && Si ==Sj)
*/class Solution {
public:
string longestPalindrome(string s) {
if(s.size() <= 1)
return s;
bool dp[1000][1000] = {false};
int Len = s.size();
int longest = 0;
int start = 0;
//init dp[i,i] = true len=1的情况
for (int i = 0; i < Len; ++i)
dp[i][i] = true;
//init dp[i, i + 1] len=2的情况
for (int i = 0; i < Len - 1; ++i)
if(s[i] == s[i + 1])
{
dp[i][i + 1] = true;
longest = 2;
start = i;
}
for (int i = Len - 3; i >= 0; --i) //从后往前考虑
for(int j = i + 2; j < Len; ++j)
{
if(dp[i + 1][j - 1] && s[i] == s[j]) //,如果前一个为true,状态转移方程
{
dp[i][j] = true;
if(longest < j - i + 1) //如果以前的长度小于这个,就更新长度。
{
longest = j - i + 1; //长度
start = i; //起点
}
}
}
return s.substr(start,longest);
}
};