forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargestPalindromeRecursive.java
56 lines (50 loc) · 1.37 KB
/
LargestPalindromeRecursive.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
45
46
47
48
49
50
51
52
53
54
55
56
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/longest-palindrome-dynamic.html
*/
package com.dsalgo;
public class LargestPalindromeRecursive
{
public static void main(String[] args)
{
String str = "acbcaccccaccc";
String result = findLargestPalindrome(str);
System.out.println(result);
}
private static String findLargestPalindrome(String str)
{
if(str==null ||str.length()==0)
return "";
boolean[][] memo = new boolean[str.length()][str.length()];
int maxStart = 0;
int maxLength = 1;
for (int startIndex = 0; startIndex < str.length(); ++startIndex)
{
memo[startIndex][startIndex] = true;
}
for (int startIndex = 0; startIndex < str.length() - 1; ++startIndex)
{
if (str.charAt(startIndex) == str.charAt(startIndex + 1))
{
memo[startIndex][startIndex + 1] = true;
maxStart = startIndex;
maxLength = 2;
}
}
for (int length = 3; length <= str.length(); ++length)
{
for (int startIndex = 0; startIndex < str.length() - length + 1; ++startIndex)
{
int endIndex = startIndex + length - 1;
if (str.charAt(startIndex) == str.charAt(endIndex)
&& memo[startIndex + 1][endIndex - 1] == true)
{
memo[startIndex][endIndex] = true;
maxStart = startIndex;
maxLength = length;
}
}
}
return str.substring(maxStart, maxStart + maxLength);
}
}