Count of Substrings having Sum equal to their Length | C # 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
using System ; using System . Collections . Generic ; class GFG { static int countSubStrings ( String s , int n ) { int count = 0 , sum = 0 ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; mp . Add ( 0 , 1 ) ; for ( int i = 0 ; i < n ; ++ i ) { sum += ( s [ i ] - '0' ) ; count += mp . ContainsKey ( sum - ( i + 1 ) ) == true ? mp [ sum - ( i + 1 ) ] : 0 ; if ( ! mp . ContainsKey ( sum - ( i + 1 ) ) ) mp . Add ( sum - ( i + 1 ) , 1 ) ; else mp [ sum - ( i + 1 ) ] = mp [ sum - ( i + 1 ) ] + 1 ; } return count ; } public static void Main ( String [ ] args ) { String str = "112112" ; int n = str . Length ; Console . Write ( countSubStrings ( str , n ) + " STRNEWLINE " ) ; } }