Question:
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.
解决:
问题的意思是在一个字符串中找到最长的回文字符串。如:给定字符串abccbe
,最长的回文字符串为bccb
,返回该字符串。
最简单的方式是暴力搜索,但是需要时间复杂度O(n^3)
,会因为时间超时而过不了。所以采用以下两种方法。
第一种使用动态规划。判断s[i][j]
(字符串从i
到j
)是否是回文,那么只要判断s[i+1][j-1] && s[i]==s[j]
即可。
public String longestPalindrome(String s) {
int length = s.length();
boolean[][] str = new boolean[length][length];
int left = 0, right = 0, max = 0;
for (int i = 0; i < length - 1; ++i){
str[i][i] = true;
str[i][i+1] = (s.charAt(i) == s.charAt(i+1));
}
str[length-1][length-1] = true;
for (int i = 2; i < length; ++i){
for (int j = 0; j + 1 < i; ++j ){
str[j][i] = str[j+1][i-1] && s.charAt(i) == s.charAt(j);
}
}
for (int i = 0; i < length; ++i){
for (int j = i + 1; j < length; ++j){
if (str[i][j] && j - i + 1 > max){
left = i;
right = j;
max = right - left;
}
}
}
return s.substring(left, right+1);
}
第二种方法,先选择一个中心点,然后向两边扩展,回文的特性决定了两边字符相等。注意:中心点可能是一个字符,如aba
的b
;也可能是两个字符中间,如abba
的bb
中心。
public String longestPalindrome(String s) {
int left = 0, right = 0;
for (int i = 0; i < s.length(); ++i){
int len1 = expand(s, i, i);
int len2 = expand(s, i, i+1);
int max = Math.max(len1, len2);
if (max > right - left + 1){
left = i- (max-1) / 2;
right = i + max / 2;
}
}
return s.substring(left, right+1);
}
int expand(String s, int center1, int center2){
int i = center1, j = center2;
int length = s.length();
int left = 0, right = 0;
while(i >= 0 && j < length && s.charAt(i) == s.charAt(j)){
left = i--;
right = j++;
}
return right - left + 1;
}
代码地址(附测试代码):
https://github.com/shichaohao/LeetCodeUsingJava/tree/master/src/longestPalindromicSubstring