Problem
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
Example
Given the string = "abcdzdcab"
, return "cdzdc"
.
Challenge
O(n2) time is acceptable. Can you do it in O(n) time.
Note
动规好题。
注意.substring(start, end)
是左闭右开区间,所以返回值里end
要+1
。if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || dp[j+1][i-1]))
这一句,要理解i - j <= 2
其实是i
和j
之间只有一个元素的情况。
循环里每一次i - j > end - start
的时候,都要更新为子串更大的情况。Time和space都是O(n^2)。
补一种中点延展的方法:循环字符串的每个字符,以该字符为中心,若两边为回文,则向两边继续延展。如此,每个字符必对应一个最长回文串。循环返回长度最长的回文串即可。
Solution
public class Solution {
public String longestPalindrome(String s) {
// Write your code here
int len = s.length();
boolean[][] dp = new boolean[len][len];
int start = 0, end = 0;
for (int i = 0; i < len; i++) {
for (int j = 0; j <= i; j++) {
if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || dp[j+1][i-1])) {
dp[j][i] = true;
if (end - start < i - j ) {
start = j;
end = i;
}
}
}
}
return s.substring(start, end+1);
}
}
方法二:中点延展
public class Solution {
String longest = "";
public String longestPalindrome(String s) {
for (int i = 0; i < s.length(); i++) {
helper(s, i, 0);
helper(s, i, 1);
}
return longest;
}
public void helper(String s, int i, int os) {
int left = i, right = i + os;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
String cur = s.substring(left+1, right);
if (cur.length() > longest.length()) {
longest = cur;
}
}
}