标签:return art longest col mil turn rom family int
给定一个字符串 s
,找到 s
中最长的回文子串。你可以假设 s
的最大长度为 1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd" 输出: "bb"
string longestPalindrome(string s) {
if (s.empty()) return "";
int len = s.size();int longest = 1;
int start = 0;
vector<vector<int> > dp(len, vector<int>(len));
for (int i = 0; i < len; i++)
{
dp[i][i] = 1;
if (i < len - 1)
{
if (s[i] == s[i + 1])
{
dp[i][i + 1] = 1;
start = i;
longest = 2;
}
}
}
for (int k = 3; k<=len ;k++)//字串長度
for (int i = 0; i < len - k+1; i++)
{
int j = i+k-1;
if (s[i] == s[j] && dp[i + 1][j - 1] == 1)
{
dp[i][j] = 1;
start = i;
longest = k;
}
}
return s.substr(start, longest);//返回字串(起始位置,長度)
}
标签:return art longest col mil turn rom family int
原文地址:https://www.cnblogs.com/binanry/p/10079668.html