Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
给出一个字符串s,找到s的最长的回文字符子串。
你可以假设s的最大长度为1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
分析:
可以用暴力搜索BF嵌套3层for循环实现,也可以用动态规划实现。
动态规划解法简单介绍:
先在DP数组里填满所有的DP[i][i]和DP[i][i+1],作为base case。

之后我们只需要填满 "??"的部分,填充“??”部分需要判断
- 左下角的格子内的值是否为true
if(DP[i+1][j-1]==true)依据: its substring is palindromic - 以及最左边和最右边的字符是否相等。
if(s[i]==s[j])依据:its start letter equals end letter.

i从n-3往0遍历,j从i往n遍历,最后就能填满DP数组。

C++实现 (Dp动态规划,O(n2))
class Solution{
public:
string longestPalindrome(string s){
if(s.size()==0) return"";
int i=0, j=0;
int n = s.size();
bool DP[n][n];
memset(DP,0,sizeof(DP));//初始化DP
//初始化2行base case
for(int i=0;i<n;i++){
DP[i][i] = true;
if(i== n-1) break;
DP[i][i+1] = (s[i]==s[i+1]);
}
//dp动态规划
for(int i = n-3; i >= 0 ;i-- ){
for(int j = i+2 ; j<n;j++){
DP[i][j] = ( DP[i+1][j-1] && s[i]==s[j]);
}
}
//截取最长的子字符串
string maxstr;
int max = 0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(DP[i][j] && j-i+1 > max ){
max = j-i+1;
maxstr = s.substr(i,max);
}
}
}
return maxstr;
}
};
640

被折叠的 条评论
为什么被折叠?



