Length of the longest substring with every character appearing even number of times | Java program for the above approach ; Function to find length of the longest subString with each element occurring even number of times ; Initialize unordered_map ; Stores the length of the longest required subString ; Traverse the String ; Stores the value of the digit present at current index ; Bitwise XOR of the mask with 1 left - shifted by val ; Check if the value of mask is already present in ind or not ; Update the final answer ; Otherwise ; Return the answer ; Driver Code ; Given String ; Length of the given String ; Function Call
import java . util . * ; class GFG { static int lenOfLongestReqSubstr ( String s , int N ) { HashMap < Integer , Integer > ind = new HashMap < > ( ) ; int mask = 0 ; ind . put ( 0 , - 1 ) ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int val = s . charAt ( i ) - '0' ; mask ^= ( 1 << val ) ; if ( ind . containsKey ( mask ) ) { ans = Math . max ( ans , i - ind . get ( mask ) ) ; } else ind . put ( mask , i ) ; } return ans ; } public static void main ( String [ ] args ) { String s = "223015150" ; int N = s . length ( ) ; System . out . print ( lenOfLongestReqSubstr ( s , N ) ) ; } }