Check if two strings are k | Optimized PHP program to check if two strings are k anagram or not . ; Function to check if str1 and str2 are k - anagram or not ; If both strings are not of equal length then return false ; Store the occurrence of all characters in a hash_array ; Store the occurrence of all characters in a hash_array ; Return true if count is less than or equal to k ; Driver code
< ? php $ MAX_CHAR = 26 ; function areKAnagrams ( $ str1 , $ str2 , $ k ) { global $ MAX_CHAR ; $ n = strlen ( $ str1 ) ; if ( strlen ( $ str2 ) != $ n ) return false ; $ hash_str1 = array ( 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ hash_str1 [ $ str1 [ $ i ] - ' a ' ] ++ ; $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ hash_str1 [ $ str2 [ $ i ] - ' a ' ] > 0 ) $ hash_str1 [ $ str2 [ $ i ] - ' a ' ] -- ; else $ count ++ ; if ( $ count > $ k ) return false ; } return true ; } $ str1 = " fodr " ; $ str2 = " gork " ; $ k = 2 ; if ( areKAnagrams ( $ str1 , $ str2 , $ k ) == true ) echo " Yes " ; else echo " No " ; ? >