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"/**
* Created by lxw, liwei4939@126.com on 2018/3/3.
*/
public class LongestPalindromicSubstring {
//动态规划法
public String longestPalindrome1(String s){
if (s == null || s.length() < 2){
return s;
}
int maxLength = 0;
String res = null;
int length = s.length();
boolean[][] dp = new boolean[length][length];
for (int i =0; i < length; i++){
dp[i][i] = true;
res = s.substring(i, i+1);
maxLength = 1;
}
for (int i = 0; i< length -1; i++){
if (s.charAt(i) == s.charAt(i+1)){
dp[i][i+1] = true;
res = s.substring(i, i+2);
maxLength = 2;
}
}
for (int len = 3; len <= length; len++){
for (int i = 0, j; (j = i+ len - 1) <= length-1; i++){
if (s.charAt(i) == s.charAt(j)){
dp[i][j] = dp[i+1][j-1];
if (dp[i][j] && maxLength < len){
res = s.substring(i, j+1);
maxLength = len;
} else {
dp[i][j] = false;
}
}
}
}
return res;
}
//中心扩展法
public String longestPalindrome2(String s){
if ( s.length() < 2){
return s;
}
int start = 0;
int end = 0;
for (int i = 0; i < s.length(); i++){
int len1 = longest(s, i, i);
int len2 = longest(s, i, i+1);
int len = Math.max(len1, len2);
if (end - start < len){
start = i - (len - 1) /2;
end = i + len /2;
}
}
return s.substring(start, end + 1);
}
private int longest(String s, int left, int right){
while (left >= 0 && right < s.length()
&& s.charAt(left) == s.charAt(right)){
left --;
right ++;
}
return right - left - 1;
}
public static void main(String[] args){
LongestPalindromicSubstring tmp = new LongestPalindromicSubstring();
String str = "babad";
String res = tmp.longestPalindrome2(str);
System.out.println(res);
}
}
283




被折叠的 条评论
为什么被折叠?



