Count of Substrings having Sum equal to their Length | Java program to implement the above approach ; Function to count the number of subStrings with sum equal to length ; Stores the count of subStrings ; Add character to sum ; Add count of subStrings to result ; Increase count of subarrays ; Return count ; Driver Code
import java . util . * ; class GFG { static int countSubStrings ( String s , int n ) { int count = 0 , sum = 0 ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; mp . put ( 0 , 1 ) ; for ( int i = 0 ; i < n ; ++ i ) { sum += ( s . charAt ( i ) - '0' ) ; count += mp . containsKey ( sum - ( i + 1 ) ) == true ? mp . get ( sum - ( i + 1 ) ) : 0 ; if ( ! mp . containsKey ( sum - ( i + 1 ) ) ) mp . put ( sum - ( i + 1 ) , 1 ) ; else mp . put ( sum - ( i + 1 ) , mp . get ( sum - ( i + 1 ) ) + 1 ) ; } return count ; } public static void main ( String [ ] args ) { String str = "112112" ; int n = str . length ( ) ; System . out . print ( countSubStrings ( str , n ) + "NEW_LINE"); } }