Encode/compress sequence of repeating integers

后端 未结 6 1437
后悔当初
后悔当初 2020-12-11 04:02

I have very long integer sequences that look like this (arbitrary length!):

0000000001110002220033333

Now I need some algorithm to convert

6条回答
  •  一个人的身影
    2020-12-11 04:17

    It is called Run Length Encoding

    Basic encoder in PHP:

    function numStringToRle($s){
        $rle = '';
        $count = 1;
        $len = strlen($s);
        for ( $i = 0; $i < $len; $i++ ){
            if ( $i != $len && $s[$i] == $s[$i+1] ){
                $count++;                
            }else{
              $rle .= chr($s[$i] + 97).$count;    
              $count = 1;
            }
        }
        return $rle;
    }
    

    Be warned it will preform badly issues with a string like

     123456789123456789
    

    If you were going to be handling a string that may have a lot of individual single characters you would be better to add some complexity and not write the length of the run if the length of the run is 1.

    //change
    $rle .= chr($s[$i] + 97).$count;    
    
    //to
    $rle .= chr($s[$i] + 97).( $count == 1 ? '' : $count );   
    
    //or
    $rle .= chr($s[$i] + 97)
    if ( $count != 1 ){
        $rle .= $count;
    }
    

提交回复
热议问题