Number of substrings with each character occurring even times | Java program for the above approach ; Function to count substrings having even frequency of each character ; Stores the count of a character ; Stores bitmask ; Stores the count of substrings with even count of each character ; Traverse the string S ; Flip the ord ( i ) - 97 bits in pre ; Increment the count by hash [ pre ] ; Increment count of pre in hash ; Return the total count obtained ; Driver code
import java . util . * ; import java . lang . * ; class GFG { static int subString ( String s , int n ) { Map < Integer , Integer > hash = new HashMap < > ( ) ; hash . put ( 0 , 1 ) ; int pre = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { pre ^= ( 1 << ( int ) ( s . charAt ( i ) - 97 ) ) ; count += hash . getOrDefault ( pre , 0 ) ; hash . put ( pre , hash . getOrDefault ( pre , 0 ) + 1 ) ; } return count ; } public static void main ( String [ ] args ) { String S = " abbaa " ; int N = S . length ( ) ; System . out . print ( subString ( S , N ) ) ; } }