#57 · Strings · Intermediate · 60 XP · about 10 min
Run-length encoding shortens text by writing each run of the same character as the character followed by the length of the run: "aabcccccaaa" becomes "a2b1c5a3". Write compress(text) that returns the encoded string.
There is one catch: if the encoded string is not strictly shorter than text, return text unchanged, because compressing it would not save anything. Uppercase and lowercase letters are different characters, and a run can be long enough to need a count with several digits.
compress("aabcccccaaa") # returns 'a2b1c5a3' compress("abc") # returns 'abc' compress("zzzzzzzzzzzz") # returns 'z12'
"abc" would turn into "a1b1c1", which is longer, so it stays as it is.
text has 0 to 100,000 characters.text contains only the letters a-z and A-Z.Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.