In: Computer Science
php please
// 2) mirrorEnds
// Complete method mirrorEnds that given a string, looks for a mirror
// image (backwards) string at both the beginning and end of the given string.
// In other words, zero or more characters at the very beginning of the given
// string, and at the very end of the string in reverse order (possibly overlapping).
// For example, "abXYZba" has the mirror end "ab".
//
// assert("" == mirrorEnds(""));
// assert("" == mirrorEnds("abcde"));
// assert("a" == mirrorEnds("abca"));
// assert("aba" == mirrorEnds("aba"));
//
function mirrorEnds($str) {
}
echo PHP_EOL . "mirrorEnds(abcdefcba) abc: " . mirrorEnds ( 'abcdefcba' ) . "\n";
assert ( 'abc' == mirrorEnds ( 'abcdefcba' ) );
echo " mirrorEnds(zzRSTzz) zz: " . mirrorEnds ( 'zzRSTzz' ) . "\n";
The code is given below followed by the output snapshot for some test cases. The basic logic used is as follows: A copy of the reversed string is made, and then compared with the original character by character - as soon as a mismatch is found, the loop is broken.
function mirrorEnds($str) {
$rev = strrev($str);
$mir_end = "";
for($i = 0; $i < strlen($str); ++$i)
{
if($rev[$i] != $str[$i])
break;
$mir_end = $mir_end . $str[$i];
}
return $mir_end;
}
echo PHP_EOL . "mirrorEnds(abcdefcba) abc: " . mirrorEnds (
'abcdefcba' ) . "\n";
echo " mirrorEnds(zzRSTzz) zz: " . mirrorEnds ( 'zzRSTzz' ) .
"\n";
echo " mirrorEnds() : " . mirrorEnds ('') . "\n";
echo " mirrorEnds(abcde) : " . mirrorEnds('abcde') . "\n";
echo " mirrorEnds('abca') a: " . mirrorEnds('abca') . "\n";
echo " mirrorEnds('aba') aba: " . mirrorEnds('aba') . "\n";