Check if two strings are k | Python3 program to check if two strings are k anagram or not . ; Function to check that is 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 ; Count number of characters that are different in both strings ; Return true if count is less than or equal to k ; Driver Code
MAX_CHAR = 26 NEW_LINE def arekAnagrams ( str1 , str2 , k ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE if ( len ( str2 ) != n ) : NEW_LINE INDENT return False NEW_LINE DEDENT count1 = [ 0 ] * MAX_CHAR NEW_LINE count2 = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT count1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT count2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( count1 [ i ] > count2 [ i ] ) : NEW_LINE INDENT count = count + abs ( count1 [ i ] - count2 [ i ] ) NEW_LINE DEDENT DEDENT return ( count <= k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " anagram " NEW_LINE str2 = " grammar " NEW_LINE k = 2 NEW_LINE if ( arekAnagrams ( str1 , str2 , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT