1-liner


  • 1

    Using a regular expression to replace repeats by numbers.

    Ruby:

    def compress(chars)
      chars.replace(chars.join.gsub(/(?<=(.))\1+/) { |s| 1 + s.size }.chars).size
    end
    

    Python version, not quite as nice/short:

    def compress(self, chars):
        chars[:] = re.sub(r'(?<=(.))\1+', lambda m: str(1 + len(m.group())), ''.join(chars))
        return len(chars)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.