text: Check if a string can be made equal to another string by swapping or replacement of characters | C ++ program for the above approach ; Function to find if given strings are same or not ; Base Condition ; Stores frequency of characters of the string str1 and str2 ; Traverse strings str1 & str2 and store frequencies in a [ ] and b [ ] ; Check if both strings have same characters or not ; If a character is present in one string and is not in another string , return false ; Sort the array a [ ] and b [ ] ; Check arrays a and b contain the same frequency or not ; If the frequencies are not the same after sorting ; At this point , str1 can be converted to str2 ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool sameStrings ( string str1 , string str2 ) { int N = str1 . length ( ) ; int M = str2 . length ( ) ; if ( N != M ) { return false ; } int a [ 256 ] = { 0 } , b [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { a [ str1 [ i ] - ' a ' ] ++ ; b [ str2 [ i ] - ' a ' ] ++ ; } int i = 0 ; while ( i < 256 ) { if ( ( a [ i ] == 0 && b [ i ] == 0 ) || ( a [ i ] != 0 && b [ i ] != 0 ) ) { i ++ ; } else { return false ; } } sort ( a , a + 256 ) ; sort ( b , b + 256 ) ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( a [ i ] != b [ i ] ) return false ; } return true ; } int main ( ) { string S1 = " cabbba " , S2 = " abbccc " ; if ( sameStrings ( S1 , S2 ) ) cout << " YES " << endl ; else cout << " ▁ NO " << endl ; return 0 ; }