DEV Community

Sharmin Shanta
Sharmin Shanta

Posted on

Check whether a given string is an anagram of another given string.

/**
 * Check if a word is an anagram of another word
 *   Break Down the Problem:
 *   a. Checking length of two given strings - return false if it doesn't match the length
 *   b. Mapping characters between two strings - Checking same char in two strings
 *   c. Counting for each character found - Same char, but checking occurrence is same between two strings
 *   d. Comparing each character count between two strings - if char and char count are same
 *
 * @param string $str1
 * @param string $str2
 * @return false|string
 */
function checkAnagram(string $str1, string $str2)
{
    $msg = '';

    try {
        $str1Count = strlen($str1);
        $str2Count = strlen($str2);

        if ($str1Count !== $str2Count) {
            return false;
        }

        $strOne = $strTwo = [];
        for ($i = 0; $i < $str1Count; $i++) {
            if (isset($strOne[$str1[$i]])) {
                $strOne[$str1[$i]]++;
            } else {
                $strOne[$str1[$i]] = 1;
            }

            if (isset($strTwo[$str2[$i]])) {
                $strTwo[$str2[$i]]++;
            } else {
                $strTwo[$str2[$i]] = 1;
            }
        }

        foreach ($strOne as $char => $count) {
            if (! isset($strTwo[$char]) || $count !== $strTwo[$char]) {
                throw new Exception("This word {$str1} is not anagram of {$str2}.");
            } else {
                $msg = "This word {$str1} is anagram of {$str2}.";
            }
        }
    } catch (Exception $ex) {
       $msg = $ex->getMessage();
    }

    return $msg;
}

/**
 * It doesn't match, why?
 * a. String length is same for given two string
 * b. Char are same in two strings
 * c. But count of char occurrence isn't same- 'c' two times in str1, and 'c' one time in str2
 * d. For matching: Just try 'act' with the word 'cat'
 */
print_r(checkAnagram('acct', 'caat'));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)