easy +8 pts

Compress Consecutive Chars

Run-length encode a string by collapsing consecutive identical characters.

Write a function `compress(s: str) -> str` that performs run-length encoding on the input string `s`. For each maximal consecutive group of identical characters, output the character followed by the group length. If a character appears only once, still output the character followed by `1`. The input string contains only lowercase English letters. Return the compressed string. Examples: - `compress("aaabbc")` returns `"a3b2c1"`. - `compress("a")` returns `"a1"`. - `compress("")` returns `""`.

Constraints

- 0 <= len(s) <= 1000 - s consists of lowercase English letters only.

Example

>>> compress("aaabbc")
'a3b2c1'
>>> compress("a")
'a1'
>>> compress("")
''
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate through the string while keeping a count of the current character.
When the character changes, append the previous character and its count, then reset the count.
Remember to flush the last group after the loop.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.