题目:
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"
算法思想:
这是一道动态规划题,当然也有更好的算法(著名的manacher(马拉车 :)算法),但是那个难度比较大,像我这样的弱菜第一次听说,基本给出动态规划的解法已经可以了。
定义bool数组d[i][j]为字符串从位置i到位置j是否为回文串。
初始状态:
d[i][j]=⎧⎩⎨⎪⎪true,true,false,i=jj=i+1且s[i]=s[j]otherwise
动态规划的状态转移方程(
j−i>=2
):
d[i][j]={true,false,s[i]=s[j]且d[i+1][j−1]=trueotherwise
C++代码如下:
class Solution {
public:
string longestPalindrome(string s) {
const int strLen = s.size();
int begin = 0,maxLen = 1;
bool d[1000][1000] = {false};
for(int i=0;i<strLen;i++)
{
d[i][i] = true;
}
for(int i = 0;i<strLen-1;i++)
{
if(s[i] == s[i+1])
{
d[i][i+1] = true;
begin = i;
maxLen = 2;
}
}
for(int len = 3;len<=strLen;len++)
{
for(int i = 0;i< strLen-len+1;i++)
{
int j = i+len-1;
if(s[i] == s[j] && d[i+1][j-1] == true)
{
d[i][j] = true;
begin = i;
maxLen = len;
}
}
}
return s.substr(begin,maxLen);
}
};