Given a string s, compress it using run-length encoding. Consecutive duplicate characters are replaced by the character followed by the count of its consecutive occurrences.
For example, the string "aaabb" is compressed to "a3b2". A single character "a" would be encoded as "a1".
Return the encoded string.
Function Signature
def encode(s: str) -> str:
...
Rules
-
Every run gets its count, including runs of length one.
-
Counts are written in decimal and can have more than one digit. Twelve
a
characters in a row become
"a12"
.
-
Characters are compared exactly, so an uppercase letter and its lowercase form are different characters:
"aA"
becomes
"a1A1"
.
-
The same character can appear in several separate runs. Each run is encoded on its own, in the order it appears.
Constraints
-
1 <= len(s) <= 10^4
-
s
consists of lowercase and/or uppercase English letters.
Examples
Input: s = "aaabb"
Output: "a3b2"
There are 3 consecutive a characters followed by 2 consecutive b characters, so the encoded string is "a3b2".
Input: s = "abcd"
Output: "a1b1c1d1"
Each character appears only once in a row, so every character is followed by 1.
Input: s = "aaAAa"
Output: "a2A2a1"
Case matters, so aa, AA and the final a are three separate runs. The last a is not merged into the first run because the AA run sits between them.