Check if characters of one string can be swapped to form other | PHP 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 Code
< ? php $ MAX = 26 ; function targetstring ( $ str1 , $ str2 ) { global $ MAX ; $ l1 = strlen ( $ str1 ) ; $ l2 = strlen ( $ str2 ) ; if ( $ l1 != $ l2 ) return false ; $ map [ $ MAX ] = array ( 0 ) ; for ( $ i = 0 ; $ i < $ l1 ; $ i ++ ) $ map [ $ str1 [ $ i ] - ' a ' ] ++ ; for ( $ i = 0 ; $ i < $ l2 ; $ i ++ ) { $ map [ $ str2 [ $ i ] - ' a ' ] -- ; if ( $ map [ $ str2 [ $ i ] - ' a ' ] < 0 ) return false ; } return true ; } $ str1 = " geeksforgeeks " ; $ str2 = " geegeeksksfor " ; if ( targetstring ( $ str1 , $ str2 ) ) echo " YES " ; else echo " NO " ; ? >