Count of sub | Function to return the count of valid sub - strings ; Variable ans to store all the possible substrings Initialize its value as total number of substrings that can be formed from the given string ; Stores recent index of the characters ; If character is a update a 's index  and the variable ans ; If character is b update b 's index  and the variable ans ; If character is c update c 's index  and the variable ans ; Driver code
function CountSubstring ( str , n ) { var ans = parseInt ( ( n * ( n + 1 ) ) / 2 ) ; var a_index = 0 ; var b_index = 0 ; var c_index = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( str [ i ] === " " ) { a_index = i + 1 ; ans -= Math . min ( b_index , c_index ) ; } else if ( str [ i ] === " " ) { b_index = i + 1 ; ans -= Math . min ( a_index , c_index ) ; } else { c_index = i + 1 ; ans -= Math . min ( a_index , b_index ) ; } } return ans ; } var str = " " . split ( " " ) ; var n = str . length ; document . write ( CountSubstring ( str , n ) ) ;