Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

How to make two strings anagram by removing characters in PHP

1 Answer

0 votes
function RemoveCharactersNeedToBeRemovedForAnagram(&$str1, &$str2) {
    $TotalABCLetters = 26;
    $count1 = array_fill(0,$TotalABCLetters,0);        
    $count2 = array_fill(0,$TotalABCLetters,0);
    $size1 = strlen($str1);
    $size2 = strlen($str2);
         
    // count char frequency str1
    for ($i = 0; $i < $size1; $i++) {
        $count1[ord($str1[$i]) - ord('a')]++;
    }
         
    // count char frequency str2
    for ($i = 0; $i < $size2; $i++) {
        $count2[ord($str2[$i]) - ord('a')]++;
    }
         
    for ($i = 0; $i < $TotalABCLetters; $i++) {
        if (abs($count1[$i] - $count2[$i]) != 0) {
            $str1 = str_replace(chr($i + 97), '', $str1); // 'a' = 97 ascii code
            $str2 = str_replace(chr($i + 97), '', $str2);
        }
    }
}
         
$str1 = "masterfx";
$str2 = "ksampret";
 
RemoveCharactersNeedToBeRemovedForAnagram($str1, $str2);

echo $str1 . "\n";
echo $str2 . "\n";
 
 
 
 
/*
run:
 
master
samret
 
*/

 





answered Oct 1, 2022 by avibootz

Related questions

...