Jerlon Jerlon - 6 months ago 10
PHP Question

Compressing a string PHP

Let's say an input a string

$a=aabbbc


$b=abbcabb


the expected output should be:
for

$a = 2a3bc

$b = a2bca2b


here is my code:

function lineEncoding($s) {

$string = str_split($s);
$counter = 0;
for($i=0;$i<count($string);$i++){
$counter = substr_count($s, $string[$i]);
if($string[$i]==$string[$i+1]){
$stringConverted .= $counter . $string[$i];
} else if($counter==1){
$stringConverted .= $string[$i];
} else {
$i++;
}
}
return $stringConverted;
}


I get an output for
$a = 2a3b
But it should be
2a3bc


$b = null


but I should've get

a2bca2b

Answer
function line_encoding($e){
    $s = preg_split("//",$e);
    $s[-1] = "";
    $o = 1;
    $f = "";
    for($c=0;$c<strlen($e);$c++){
        if($s[$c]==$s[$c-1]){
            $o++;
        }else{
            $f .= $o==1?$s[$c-1]:($o.$s[$c-1]);
            $o=1;
        }
    }
    return $f;
}

Check if this works