// Java code to find the maximum length of
// sub-string (of even length) which can be
// arranged into a Palindrome
import java.io.*;
import java.util.*;
class GFG
{
static HashMap<Integer, Integer> count = new HashMap<>();
// function that returns true if the given
// sub-string can be arranged into a Palindrome
static boolean canBePalindrome(HashMap<Integer, Integer> count)
{
for (HashMap.Entry<Integer, Integer> entry : count.entrySet())
if ((entry.getValue() & 1) == 1)
return false;
return true;
}
// This function returns the maximum length of
// the sub-string (of even length) which can be
// arranged into a Palindrome
static int maxPal(String str, int start, int end,
HashMap<Integer, Integer> count)
{
// If we reach end of the string
if (end == str.length())
{
// if string is of even length
if ((end - start) % 2 == 0)
// if string can be arranged into a
// palindrome
if (canBePalindrome(count))
return end - start;
return 0;
}
else
{
// Even length sub-string
if ((end - start) % 2 == 0)
{
// Check if current sub-string can be
// arranged into a palindrome
if (canBePalindrome(count))
{
count.put((int) str.charAt(end),
count.get((int) str.charAt(end)) ==
null ? 1 : count.get((int) str.charAt(end)) + 1);
return Math.max(end - start,
maxPal(str, start, end + 1, count));
}
else
{
count.put((int) str.charAt(end),
count.get((int) str.charAt(end)) ==
null ? 1 : count.get((int) str.charAt(end)) + 1);
return maxPal(str, start, end + 1, count);
}
}
// Odd length sub-string
else
{
count.put((int) str.charAt(end),
count.get((int) str.charAt(end)) ==
null ? 1 : count.get((int) str.charAt(end)) + 1);
HashMap<Integer, Integer> c = new HashMap<>(count);
int length = maxPal(str, start, end + 1, c);
count.put((int) str.charAt(end),
count.get((int) str.charAt(end)) ==
null ? -1 : count.get((int) str.charAt(end)) - 1);
count.put((int) str.charAt(start),
count.get((int) str.charAt(start)) ==
null ? -1 : count.get((int) str.charAt(start)) - 1);
return Math.max(length, maxPal(str,
start + 1, end, count));
}
}
}
// Driver Code
public static void main(String[] args)
{
String str = "124565463";
int start = 0, end = 0;
System.out.println(maxPal(str, start, end, count));
}
}
// This code is contributed by
// sanjeev2552