leetcode[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.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
Solution1(DP)
public class Solution {
public String longestPalindrome(String s) {
//DP
if(s == null || s.isEmpty()){
return "";
}
int n = s.length() ;
int maxI = 0 ;
int maxJ = 0 ;
boolean [][] isPa = new boolean [n][n];
for(int i = 0 ; i < n ; i ++){
isPa [i][i] = true ;
if((i + 1 ) < n && s.charAt(i) == s.charAt(i + 1)){
isPa[i][i + 1] = true ;
maxI = i ;
maxJ = i + 1 ;
}
}
//assume l >= 3
for(int l = 3 ; l <= n ; l ++){
for(int i = 0 ; i < n - l + 1 ; i ++){//i < n - l + 1
int j = i + l - 1;//pay attention to array's bound
isPa[i][j] = (isPa[i + 1 ][j - 1] && s.charAt(i) == s.charAt(j));//字符串[i,j]是回文的当且仅当[i+1,j-1]是回文的且字符i等于字符j
if(isPa[i][j]){
maxI = i ;
maxJ = j ;
}
}
}
return s.substring(maxI , maxJ + 1);
}
}
Solution2:(往回文字符串的两边拓展寻找更长的回文字符串)
public class Solution {
public String longestPalindrome(String s) {
if (s == null) {
return "";
}
char[] arr = s.toCharArray();
int max = 0;
int maxi = 0;
int maxj = 0;
int len = arr.length;
for (int i = 0; i < len;) {
int i1 = getFarestSameElementIndex(arr, i,len);
int dist = getDistance(arr, i, i1,len);
int index1 = i - dist;
int index2 = i1 + dist;
int l = index2 - index1;
if (l > max) {
max = l;
maxi = index1;
maxj = index2;
}
i = i1 + 1;//jump over the same chars
}
return s.substring(maxi, maxj + 1);
}
//以[index1,index2]作为已经是回文的字符串,想两边拓展,返回最大拓展距离
private int getDistance(char[] arr, int index1, int index2,int len) {
int i1 = index1 - 1;
int i2 = index2 + 1;
int dist = 0;
while (i1 >= 0 && i2 < len) {
if (arr[i1] == arr[i2]) {
dist++;
} else {
break;
}
i1--;
i2++;
}
return dist;
}
//返回index开始的相同字符的最大长度
private int getFarestSameElementIndex(char[] arr, int index,int len) {
for (int i = index + 1; i < len; i++) {
if (arr[i] != arr[index]) {
return i - 1;
}
}
return len - 1;
}
}

浙公网安备 33010602011771号