题目描述
题目链接:5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
例子
例子 1
Input: “babad” Output: bab" Explanation: “aba” is also a valid answer.
例子 2
Input: “cbbd” Output: “bb”
解题思路
这道题可以采用动态规划的思路来做,创建一个二维数组 isPalindrome[len][len]
其中 isPalindrome[i][j]
表示 s[i]
到 s[j]
之间构成的子串是否为回文。接下来只需要填满 isPalindrome
的上三角部分即可(j >= i
的部分),对任意 i
和 j
有下列转移方程:
s[i] != s[j]
:边缘两个字符不相等,肯定不是回文,isPalindrome[i][j] = false
s[i] == s[j] && step <= 1
:长度为 1 或者 2的子串,边缘字符相同即为回文,isPalindrome[i][j] = true
s[i] == s[j] && step > 1
:长度大于 2,因此除了判断边缘字符是否相同,我们还需要判断去掉边缘两字符后的子串是否为回文,isPalindrome[i][j] = isPalindrome[i + 1][j - 1]
我们可以发现,isPalindrome[i][j]
很大程度上取决于 isPalindrome[i + 1][j - 1]
,即往左下方偏移一个位置,因此我们要保证正确的遍历顺序,这里正确的遍历方式应该是从对角线开始,不断往右上方遍历。
同时,这种方法还可以以滑动窗口的思路来想,首先用长度为 1 的滑动窗口遍历取得所有子串判断是否为子串(长度为1肯定是子串);再用长度为 2 的滑动窗口遍历判断是否为子串,以此类推。
代码如下:
#include <vector>
#include <string>
class Solution {
public:
std::string longestPalindrome(std::string s) {
if (s.empty()) return "";
size_t len = s.length();
// isPalindrome[i][j] indicate if s[i] to s[j] construct a palindrome
std::vector<std::vector<bool>> isPalindrome(len, std::vector<bool>(len, false));
// result substring begin & length
int begin = 0;
int maxLen = 1;
int step = 0;
while (step < len) {
for (int i = 0; i < len; i++) {
if (i + step >= len) break;
if (s[i] != s[i + step]) continue;
if (step <= 1 || s[i + 1] == s[i + step - 1]) {
isPalindrome[i][i + step] = true;
if (step > maxLen) {
maxLen = step;
begin = i;
}
}
}
}
return s.substr(begin, maxLen);
}
};
- 时间复杂度: O(n ^ 2)
- 空间复杂度: O(n ^ 2)
GitHub 代码同步地址: 5.LongestPalindromicSubstring.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions