Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
method dp
字符串回文dp,思维方式在Leetcode 131. Palindrome Partitioning已经讨论过,如果想让第i-j之间的字符串为回文的话,那么要求i+1-j-1之间的字符串也为回文。
这里的遍历逻辑是先以1个为单位遍历,再以2个字符为单位遍历,直到以k个字符为单位为遍历,dp[i][j]表示第i到第j个的子字符串是否为回文。只能这样遍历,因为必须知道第i+1~j-1的状态,才能知道i-j的状态。
class Solution {
public:
string longestPalindrome(string s) {
string ans = "";
int start = 0;
int end = 0;
vector<vector<bool>> dp;
dp.resize(s.size(), vector<bool>(s.size(), false));
for (int k = 0; k < s.size(); k++) {
for (int i = 0; i < s.size(); i++) {
int j = i + k;
if (j > s.size()) break;
if (j == i) dp[i][j] = true;
else if (j - 1 == i) {
if (s[i] == s[j]) {
dp[i][j] = true;
if (j - i > end - start) {
end = j;
start = i;
}
}
}
else {
if (s[i] == s[j] && dp[i + 1][j - 1]) {
dp[i][j] = true;
if (j - i > end - start) {
end = j;
start = i;
}
}
}
}
}
return s.substr(start, end - start + 1);
}
method 2 Expand Around Center
遍历数组时,从第i个字符出发,分别从两边遍历,直到找到以i为中心的最长回文。
总觉得这道题没必要用dp,直接遍历,用dp反而更麻烦了。
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
method 3 马拉车算法 Manacher’s Algorithm
summary
- 字符串回文dp
- dp[i][j]表示从第i-j的状态。
- 从中心出发,向两边进行遍历