Before trying to solve it, please make sure you have comprehended the constraint in description completely:
"Replace any maximal sequence of n 1’s with the binary version of n whenever it shortens the length of the message."