Count of substrings of a string containing another given string as a substring | Set 2 | Function to count the substrings of string containing another given string as a substring ; Store length of string S ; Store length of string T ; Store the required count of substrings ; Store the starting index of last occurence of T in S ; Iterate in range [ 0 , n1 - n2 ] ; Check if substring from i to i + n2 is equal to T ; Check if substring from i to i + n2 is equal to T ; Mark chk as false and break the loop ; If chk is true ; Add ( i + 1 - last ) * ( n1 - ( i + n2 - 1 ) ) to answer ; Update the last to i + 1 ; Prlet the answer ; Driver Code ; Function Call
function findOccurrences ( S , T ) { let n1 = S . length ; let n2 = T . length ; let ans = 0 ; let last = 0 ; for ( let i = 0 ; i <= n1 - n2 ; i ++ ) { let chk = true ; for ( let j = 0 ; j < n2 ; j ++ ) { if ( T [ j ] != S [ i + j ] ) { chk = false ; break ; } } if ( chk ) { ans += ( i + 1 - last ) * ( n1 - ( i + n2 - 1 ) ) ; last = i + 1 ; } } document . write ( ans ) ; } let S = " " , T = " " ; findOccurrences ( S , T ) ;