您的位置:首页 > 其它

算法分析与设计丨第十五周丨LeetCode(19)——Longest Palindromic Substring(Medium)

2017-12-13 21:09 597 查看
题目描述:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:
Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.


Example:
Input: "cbbd"

Output: "bb"


题目解析:

动态规划。题目做得有点丑陋。核心思想是先看长度为1和2的回文串,然后从长度为3到size - 1遍历,如果发现减去头和尾的字串是回文并且头和尾的字母相等,则将其加入回文串中。

class Solution {
public:
string longestPalindrome(string s) {
int size = s.size();

vector<vector<int> > dp(size,vector<int>(size,0));

int max_left = 0,max_right = 0;
string max_substr = "";

for(int i = 0;i < size;++i)
{
dp[i][i] = 1;
if(i != size - 1 && s[i] == s[i + 1])
{
dp[i][i + 1] = 1;
//the length of 2 is Palindromic
max_left = i;
max_right = i + 1;
}

}

for(int strlen = 3; strlen <= size;++strlen)
{

for(int i = 0;i <= size - strlen;++i)
{
int j = i + strlen - 1;
if(dp[i + 1][j - 1] == 1 && s[i] == s[j])
{
dp[i][j] = 1;
string temp = s.substr(i,strlen);
if(temp.size() > max_right - max_left + 1)
{

max_left = i;
max_right = j;
max_substr = temp;
}

}

}
}

b
9fd2
ool flag = false;
if(max_left == 0 && max_right == 0 || max_right - max_left == 1)
{
for(int i = 0;i < size - 1;++i)
{
if(dp[i][i + 1] == 1)
{
max_substr = s.substr(i,2);
flag = true;
break;
}
}
}

if(max_left == 0 && max_right == 0 && flag == false)
return s.substr(0,1);

return max_substr;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: