Count distinct substrings that contain some characters at most k times | js implementation of the approach ; Function to return the count of valid sub - strings ; Store all characters of anotherStr in a direct index table for quick lookup . ; To store distinct output substrings ; Traverse through the given string and one by one generate substrings beginning from s [ i ] . ; One by one generate substrings ending with s [ j ] ; If character is illegal ; If current substring is valid ; If current substring is invalid , adding more characters would not help . ; Return the count of distinct sub - strings ; Driver code
let MAX_CHAR = 256 ; function countSubStrings ( s , anotherStr , k ) { let illegal = [ ] ; for ( let i = 0 ; i < 256 ; i ++ ) illegal . push ( false ) ; for ( let i = 0 ; i < anotherStr . length ; i ++ ) illegal [ anotherStr [ i ] ] = true ; let us = new Set ( ) ; for ( let i = 0 ; i < s . length ; ++ i ) { let ss = " " ; let count = 0 ; for ( let j = i ; j < s . length ; ++ j ) { if ( illegal [ s [ j ] ] ) ++ count ; ss = ss + s [ j ] ; if ( count <= k ) { us . add ( ss ) ; } else break ; } } return us . size ; } let str = " " ; let anotherStr = " " ; let k = 2 ; document . write ( countSubStrings ( str , anotherStr , k ) ) ;