Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.面试
Example1:算法
Input: "babad"编程
Output: "bab"bash
Note: "aba" is also a valid answer.学习
Example2:ui
Input: "cbbd"spa
Output: "bb"3d
Example1: 输入: "babad"code
输出: "bab"orm
注意: "aba" 是一个有效答案.
Example2:
输入: "cbbd"
输出: "bb"
通常开发者,能想到的最快速的方法,就是找到"最长公共子串".
"反转S并成为S',找到S和S'之间的最长公共子串.它也必须是最长的回文子串"
注意: 若是咱们并非全部的最长公共子串,就必定是最长回文子串.
因此,若是只是单纯的查找最长公共子串方法,是不可行的.可是,若是去修改这个问题?
思路: 在咱们找到一个最长的公共子串候选者时,咱们检查子串的索引是否与反向子串的原始索引相同.若是是,那么尝试更新到目前为止发现的最长的回文.若是没有,咱们就跳过这个,寻找下个候选回文子串.
Si...Sj
是回文,则定义P[i,j]
为真,不然为假P[i,j] <-- (p[i+1,j-1] 和 Si = Sj)
;时间复杂度:O(N*N)
空间复杂度:O(N*N)
C Code
string longestPalindromeDP(string s) {
int n = s.length();
int longestBegin = 0;
int maxLen = 1;
bool table[1000][1000] = {false};
for (int i = 0; i < n; i++) {
table[i][i] = true;
}
for (int i = 0; i < n-1; i++) {
if (s[i] == s[i+1]) {
table[i][i+1] = true;
longestBegin = i;
maxLen = 2;
}
}
for (int len = 3; len <= n; len++) {
for (int i = 0; i < n-len+1; i++) {
int j = i+len-1;
if (s[i] == s[j] && table[i+1][j-1]) {
table[i][j] = true;
longestBegin = i;
maxLen = len;
}
}
}
return s.substr(longestBegin, maxLen);
}
复制代码
尝试画图->阅读代码