text: Check if a string can be formed from another string using given constraints | Function to check if S2 can be formed of S1 ; Length of Strings ; hash - table to store count ; Store count of each character ; Traverse and check for every character ; If the character of s2 is present in s1 ; If the character of s2 is not present in S1 , then check if previous two ASCII characters are present in S1 ; Driver Code ; Calling function to check
code: function check ( S1 , S2 ) { var n1 = S1 . length ; var n2 = S2 . length ; var mp = { } ; for ( var i = 0 ; i < n1 ; i ++ ) { if ( mp . hasOwnProperty ( S1 [ i ] ) ) { mp [ S1 [ i ] ] = mp [ S1 [ i ] ] + 1 ; } else { mp [ S1 [ i ] ] = 1 ; } } for ( var i = 0 ; i < n2 ; i ++ ) { if ( mp . hasOwnProperty ( S2 [ i ] ) ) { mp [ S2 [ i ] ] = mp [ S2 [ i ] ] - 1 ; } else if ( mp . hasOwnProperty ( String . fromCharCode ( S2 [ i ] . charCodeAt ( 0 ) - 1 ) ) && mp . hasOwnProperty ( String . fromCharCode ( S2 [ i ] . charCodeAt ( 0 ) - 2 ) ) ) { mp [ String . fromCharCode ( S2 [ i ] . charCodeAt ( 0 ) - 1 ) ] = mp [ String . fromCharCode ( S2 [ i ] . charCodeAt ( 0 ) - 1 ) ] - 1 ; mp [ String . fromCharCode ( S2 [ i ] . charCodeAt ( 0 ) - 2 ) ] = mp [ String . fromCharCode ( S2 [ i ] . charCodeAt ( 0 ) - 2 ) ] - 1 ; } else { return false ; } } return true ; } var S1 = " " ; var S2 = " " ; if ( check ( S1 , S2 ) ) document . write ( " " ) ; else document . write ( " " ) ;