Longest Substring that can be made a palindrome by swapping of characters | Java program for the above approach ; Function to find the Longest substring that can be made a palindrome by swapping of characters ; Initialize dp array of size 1024 ; Initializeing dp array with length of s ; Initializing mask and res ; Traverse the string ; Find the mask of the current character ; Finding the length of the longest substring in s which is a palindrome for even count ; Finding the length of the longest substring in s which is a palindrome for one odd count ; Finding maximum length of substring having one odd count ; dp [ mask ] is minimum of current i and dp [ mask ] ; Return longest length of the substring which forms a palindrome with swaps ; Driver Code ; Input String ; Function Call
import java . io . * ; import java . util . * ; class GFG { public static int longestSubstring ( String s ) { int dp [ ] = new int [ 1024 ] ; Arrays . fill ( dp , s . length ( ) ) ; int res = 0 , mask = 0 ; dp [ 0 ] = - 1 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { mask ^= 1 << ( s . charAt ( i ) - '0' ) ; res = Math . max ( res , i - dp [ mask ] ) ; for ( int j = 0 ; j <= 9 ; ++ j ) res = Math . max ( res , i - dp [ mask ^ ( 1 << j ) ] ) ; dp [ mask ] = Math . min ( dp [ mask ] , i ) ; } return res ; } public static void main ( String [ ] args ) { String s = "3242415" ; System . out . println ( longestSubstring ( s ) ) ; } }