Run length
Level A. Teaches runs() and building a Str with interpolation.
You are given a word of lowercase letters, at most 10⁵ long. Replace each maximal run of equal letters by the letter and the run's length. For aaabcc print a3b1c2.
Input: the word. Output: the encoded word.
| Input | Output |
|---|---|
aaabcc | a3b1c2 |
5 tests · Ctrl+Enter
Hints
s.runs()walks each maximal stretch of equal letters as a slice ofs:r.first!is its letter andr.lenits length."{r.first!}{r.len}"turns the letter and the count into text; integers have no.to_str()."".join(...)on[... for r in s.runs()]glues the pieces together, and the whole scan is O(n).- Strings and output covers
Str,Charand interpolation.