function isAnagram($word1, $word2) { if (empty($word1) || empty($word1) || strlen($word1) != strlen($word2)) { // check for empty strings or if // one of the words atleast has one or more chars more than the other return false; } else { $charFreqMapWord1 = __buildFrequencyMap($word1); print_r($charFreqMapWord1); $charFreqMapWord2 = __buildFrequencyMap($word2); print_r($charFreqMapWord2); foreach ($charFreqMapWord1 as $char => $count) { if (isset($charFreqMapWord2[$char]) && $charFreqMapWord2[$char] == $count) { continue; } else { return false; } } return true; } }
function removeDuplicateCharacters($word) { if (empty($word)) { // defensive return $word; } // length of the given word $wordLength = strlen($word); if ($wordLength == 1) { // special case return $word; } $chars = __buildFrequencyMap($word); // PHP associative arrays do maintain the order of insertion. // So simply iterate and the unique chars found in the word. $result = ""; foreach ($chars as $key => $value) { $result .= $key; } return $result; }