Encode/compress sequence of repeating integers

后端 未结 6 1419
后悔当初
后悔当初 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:33

    $str="0000000001110002220033333";
    
    //$c will count the number of occurances.
    
    $c=1;
    
    $lastInt=substr($str,0,1);
    
    $str=substr($str,1);
    
    $resultStr='';
    
    $loopEnd=strlen($str);
    
    
    for($i=1; $i<=$loopEnd+1;$i++)
    
    {
    
        $nowInt=substr($str,0,1);   
        if($lastInt==$nowInt)
        {
            $c++;
            $str=substr($str,1);
        }
        else
        {
            $char=chr((int)$lastInt + 97);
            $resultStr=$resultStr.$char.$c;
            $str=substr($str,1);
            $c=1;
            $lastInt=$nowInt;
        }
    }
    
    // we use if condition since for loop will not take the last integer if it repeats.
    
    if($c>1)
    {
    
    $char=chr((int)$lastInt + 97);
    
    $resultStr=$resultStr.$char.$c;
    
    }
    
    echo $resultStr;
    

提交回复
热议问题