Different substrings in a string that start and end with given strings | function to return number of different sub - strings ; initially our answer is zero . ; find the length of given strings ; currently make array and initially put zero . ; find occurrence of " a " and " b " in string " s " ; We use a hash to make sure that same substring is not counted twice . ; go through all the positions to find occurrence of " a " first . ; if we found occurrence of " a " . ; then go through all the positions to find occurrence of " b " . ; if we do found " b " at index j then add it to already existed substring . ; if we found occurrence of " b " . ; now add string " b " to already existed substring . ; If current substring is not included already . ; put any non negative integer to make this string as already existed . ; make substring null . ; return answer . ; Driver Code
function numberOfDifferentSubstrings ( s , a , b ) { let ans = 0 ; let ls = s . length ; let x = new Array ( ls ) ; let y = new Array ( ls ) ; for ( let i = 0 ; i < ls ; i ++ ) { x [ i ] = 0 ; y [ i ] = 0 ; } for ( let i = 0 ; i < ls ; i ++ ) { if ( s [ i ] == a ) x [ i ] = 1 ; if ( s [ i ] == b ) y [ i ] = 1 ; } let hash = new Set ( ) ; let curr_substr = " " ; for ( let i = 0 ; i < ls ; i ++ ) { if ( x [ i ] != 0 ) { for ( let j = i ; j < ls ; j ++ ) { if ( y [ j ] == 0 ) curr_substr += s [ i ] ; if ( y [ j ] != 0 ) { curr_substr += s [ j ] ; if ( ! hash . has ( curr_substr ) ) ans ++ ; hash . add ( curr_substr ) ; } } curr_substr = " " ; } } return ans ; } let s = " " ; let begin = ' ' ; let end = ' ' ; document . write ( numberOfDifferentSubstrings ( s , begin , end ) ) ;