Count all substrings having character K | Function to return the index of the next occurrence of character ch in str starting from the given index ; Return the index of the first occurrence of ch ; No occurrence found ; Function to return the count of all the substrings of str which contain the character ch at least one ; To store the count of valid substrings ; Index of the first occurrence of ch in str ; No occurrence of ch after index i in str ; Substrings starting at index i and ending at indices j , j + 1 , ... , n - 1 are all valid substring ; Driver code
function nextOccurrence ( str , n , start , ch ) { for ( var i = start ; i < n ; i ++ ) { if ( str [ i ] === ch ) return i ; } return - 1 ; } function countSubStr ( str , n , ch ) { var cnt = 0 ; var j = nextOccurrence ( str , n , 0 , ch ) ; for ( var i = 0 ; i < n ; i ++ ) { while ( j !== - 1 && j < i ) { j = nextOccurrence ( str , n , j + 1 , ch ) ; } if ( j === - 1 ) break ; cnt += n - j ; } return cnt ; } var str = " " ; var n = str . length ; var ch = " " ; document . write ( countSubStr ( str , n , ch ) ) ;