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