I have a solution, which compares 2 given strings and returns the number of total matching characters.
I know I haven't initialized the variables and arrays and that this (correctly) yields warnings. I know the variables aren't self-explanatory as they should be.
function commonCharacterCount($s1, $s2) {
$a = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
$b = (strlen($s1) > strlen($s2)) ? $s1 : $s2;
foreach(count_chars($a, 1) as $i => $v) {
$c[chr($i)] = $v;
}
foreach (count_chars($b, 1) as $i => $v) {
$d[chr($i)] = $v;
}
$t = 0;
foreach($c as $k => $v) {
if($c[$k] <= $d[$k]) {
$t += $c[$k];
} else {
$t += $d[$k];
}
}
return $t;
}
For instance, I have the two strings:
$s1 = "abacadeee";
and $s2 = "aabbccddee";
, the expected output would be 7
.
As required, this solution works so far and you can test it here: sandbox
Which steps are unnecessary and how can I improve this algorithm?