-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindrome.java
More file actions
54 lines (41 loc) · 837 Bytes
/
LongestPalindrome.java
File metadata and controls
54 lines (41 loc) · 837 Bytes
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
45
46
47
48
49
50
51
52
53
54
public class LongestPalindrome {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String longestPalindrome(String s) {
// i, j, from i to j inclusive. this is a palindrome
int len = s.length();
if(len <=1) return s;
boolean[][] dp = new boolean[len][len];
int start = 0;
int end = 0;
for(int i = len-1; i>=0; i--)
{
for(int j =i; j<len;j++)
{
dp[i][j] = false;
if(j==i)
{
dp[i][j] = true;
}
else if(j-i==1)
{
dp[i][j] = (s.charAt(i) == s.charAt(j));
}
else if(j-i>=2)
{
dp[i][j] = dp[i+1][j-1]&&(s.charAt(i) == s.charAt(j));
}
if(dp[i][j]&&j-i>end -start)
{
start = i;
end = j;
}
}
}
return s.substring(start, end+1);
}
}