Encode/compress sequence of repeating integers

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

    Here is a naive implementation of what you want.

    $toEncode = '0000000001110002220033333';
    $currentChar = '-1';
    $length = strlen($toEncode);
    $encoded = '';
    $currentNbrChar = 0;
    for($i = 0; $i < $length; $i++){
      if($toEncode[$i] != $currentChar){
        if($currentChar != '-1'){
          $encoded .= chr(97 + $currentChar).$currentNbrChar;
        }
        $currentNbrChar = 0;
        $currentChar = $toEncode[$i];
      }
      $currentNbrChar ++;
    }
    if($currentChar != '-1'){
      $encoded .= chr(97 + $currentChar).$currentNbrChar;
    }
    echo $encoded;
    

提交回复
热议问题