Check if characters of one string can be swapped to form other | C ++ program to check if characters of one string can be swapped to form other ; if length is not same print no ; Count frequencies of character in first string . ; iterate through the second string decrement counts of characters in second string ; Since lengths are same , some value would definitely become negative if result is false . ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; bool targetstring ( string str1 , string str2 ) { int l1 = str1 . length ( ) ; int l2 = str2 . length ( ) ; if ( l1 != l2 ) return false ; int map [ MAX ] = { 0 } ; for ( int i = 0 ; i < l1 ; i ++ ) map [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < l2 ; i ++ ) { map [ str2 [ i ] - ' a ' ] -- ; if ( map [ str2 [ i ] - ' a ' ] < 0 ) return false ; } return true ; } int main ( ) { string str1 = " geeksforgeeks " ; string str2 = " geegeeksksfor " ; if ( targetstring ( str1 , str2 ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }