Encode/compress sequence of repeating integers

后端 未结 6 1420
后悔当初
后悔当初 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's a shorter version:

    function smush(str) {
      return str.replace(/((.)\2*)/g, function(_, w, x) {
        return x + w.length;
      });
    }
    

    edit oh I see you want to encode with php; sorry I don't know that. Here's a decoder in a similar spirit:

    function unsmush(str) {
      return str.replace(/(.)(\d+)/g, function(_, x, n) {
        return new Array(parseInt(n, 10) + 1).join(x);
      });
    }
    

提交回复
热议问题