/
LongestPalindromicSubstring.java
44 lines (38 loc) · 1.25 KB
/
LongestPalindromicSubstring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.cwind.leetcode.dp;
/**
* Created with IntelliJ IDEA.
* User: Cwind
* Date: 2015/6/29
* Email: billchen01@163.com
* #5 - Medium
*/
public class LongestPalindromicSubstring {
//Dynamic Programming Solution
public String longestPalindrome(String s){
if(s.length()<=1){
return s;
}
int start=0, end=0;
int maxLen = 0;
boolean[][] plain = new boolean[s.length()][s.length()];
for(int i=s.length()-1;i>=0;i--){
for(int j=i;j<s.length();j++){
if(s.charAt(i)==s.charAt(j)&&(j-i<=2||plain[i+1][j-1])){
plain[i][j]=true;
if(maxLen<j-i+1){
maxLen = j-i+1;
start = i;
end = j;
}
}
}
}
return s.substring(start, end+1);
}
public static void main(String[] args){
LongestPalindromicSubstring tester = new LongestPalindromicSubstring();
System.out.println(tester.longestPalindrome("zeusnilemacaronimaisanitratetartinasiaminoracamelinsuez"));
System.out.println(tester.longestPalindrome("abbac"));
System.out.println(tester.longestPalindrome("caba"));
}
}