text: Check if a given string can be converted to another by given possible swaps | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkStr1CanConStr2 ( string & str1 , string & str2 ) { int N = str1 . length ( ) ; int M = str2 . length ( ) ; set < int > st1 ; set < int > st2 ; int hash1 [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { hash1 [ str1 [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { st1 . insert ( str1 [ i ] ) ; } for ( int i = 0 ; i < M ; i ++ ) { st2 . insert ( str2 [ i ] ) ; } if ( st1 != st2 ) { return false ; } int hash2 [ 256 ] = { 0 } ; for ( int i = 0 ; i < M ; i ++ ) { hash2 [ str2 [ i ] ] ++ ; } sort ( hash1 , hash1 + 256 ) ; sort ( hash2 , hash2 + 256 ) ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( hash1 [ i ] != hash2 [ i ] ) { return false ; } } return true ; } int main ( ) { string str1 = " xyyzzlll " ; string str2 = " yllzzxxx " ; if ( checkStr1CanConStr2 ( str1 , str2 ) ) { cout << " True " ; } else { cout << " False " ; } }