Count of substrings of a given Binary string with all characters same | Function to count number of sub - strings of a given binary string that contains only 1 ; Iterate untill L and R cross each other ; Check if reached the end of string ; Check if encountered '1' then extend window ; Check if encountered '0' then add number of strings of current window and change the values for both l and r ; Return the answer ; Function to flip the bits of string ; Function to count number of sub - strings of a given binary string that contains only 0 s & 1 s ; count of substring which contains only 1 s ; Flip the character of string s 0 to 1 and 1 to 0 to count the substring with consecutive 0 s ; count of substring which contains only 0 s ; Given string str ; Function Call
function countSubAllOnes ( s ) { var l = 0 , r = 0 , ans = 0 ; while ( l <= r ) { if ( r == s . length ) { ans += ( ( r - l ) * ( r - l + 1 ) ) / 2 ; break ; } if ( s [ r ] == ' ' ) r ++ ; else { ans += ( ( r - l ) * ( r - l + 1 ) ) / 2 ; l = r + 1 ; r ++ ; } } return ans ; } function flip ( s ) { for ( var i = 0 ; s [ i ] ; i ++ ) { if ( s [ i ] == ' ' ) s [ i ] = ' ' ; else s [ i ] = ' ' ; } return s ; } function countSubAllZerosOnes ( s ) { var only_1s = countSubAllOnes ( s ) ; s = flip ( s . split ( ' ' ) ) ; var only_0s = countSubAllOnes ( s ) ; return only_0s + only_1s ; } var s = " " ; document . write ( countSubAllZerosOnes ( s ) ) ;