Encode/compress sequence of repeating integers

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

    function compress( $str) {
    $strArr = str_split($str.'0');
    $count = 0;
    $resStr = '';
    $strCheck = $strArr[0];
    foreach($strArr as $key => $value)
    {
        if($strCheck == $value)
        {
           $count++;
        } 
        else
        {
            if($count == 1)
            {
                $strCheck = $value;
                $resStr .= $strArr[$key-1];
                $count=1;
            }
            elseif($count == 2)
            {
                $strCheck = $value;
                $resStr .= $strArr[$key-1].$strArr[$key-1];
                $count=1;
            }
            else
            {
                $strCheck = $value;
                $resStr .= $strArr[$key-1].$count;
                $count=1;
            }
        } 
    
    } 
    return $resStr;
    

    }

提交回复
热议问题