text: Check if a given string can be converted to another by given possible swaps | Javascript program to implement the above approach ; Stores length of str1 ; Stores length of str2 ; Stores distinct characters of str1 ; Stores distinct characters of str2 ; Stores frequency of each character of str1 ; Traverse the string str1 ; Update frequency of str1 [ i ] ; Traverse the string str1 ; Insert str1 [ i ] into st1 ; Traverse the string str2 ; Insert str1 [ i ] into st1 ; If distinct characters in str1 and str2 are not same ; Stores frequency of each character of str2 ; Traverse the string str2 ; Update frequency of str2 [ i ] ; Sort hash1 [ ] array ; Sort hash2 [ ] array ; Traverse hash1 [ ] and hash2 [ ] ; If hash1 [ i ] not equal to hash2 [ i ] ; Driver Code
code: function checkStr1CanConStr2 ( str1 , str2 ) { var N = str1 . length ; var M = str2 . length ; var st1 = new Set ( ) ; var st2 = new Set ( ) ; var hash1 = Array ( 256 ) . fill ( 0 ) ; for ( var i = 0 ; i < N ; i ++ ) { hash1 [ str1 [ i ] . charCodeAt ( 0 ) ] ++ ; } for ( var i = 0 ; i < N ; i ++ ) { st1 . add ( str1 [ i ] ) ; } for ( var i = 0 ; i < M ; i ++ ) { st2 . add ( str2 [ i ] ) ; } if ( st1 . size != st2 . size ) { return false ; } var hash2 = Array ( 256 ) . fill ( 0 ) ; for ( var i = 0 ; i < M ; i ++ ) { hash2 [ str2 [ i ] . charCodeAt ( 0 ) ] ++ ; } hash1 . sort ( ( a , b ) => a - b ) ; hash2 . sort ( ( a , b ) => a - b ) ; for ( var i = 0 ; i < 256 ; i ++ ) { if ( hash1 [ i ] != hash2 [ i ] ) { return false ; } } return true ; } var str1 = " " ; var str2 = " " ; if ( checkStr1CanConStr2 ( str1 , str2 ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }