How to find the maximum number of characters between any two same character in a string with PHP

1 Answer

0 votes
function GetMaxChars($str) {
    $size = strlen($str);
    $maxCh = 0;
    
    for ($i = 0; $i < $size - 1; $i++) {
        for ($j = $i + 1; $j < $size; $j++) {
            if ($str[$i] == $str[$j]) {
                $temp = abs($j - $i - 1);
                $maxCh = $maxCh > $temp ? $maxCh : $temp;
            }
        }
    }
    return $maxCh;
}

$str = "aBcaaBdefBgh";

echo GetMaxChars($str);




/*
run:

7

*/

 



answered Dec 18, 2022 by avibootz
...