Run-Length Encode Consecutive Letter Runs
Problem statement
Run-length encode s by replacing each maximal consecutive run of the same character with that character followed by its decimal run length. Process the runs from left to right.
For this exercise, s contains only uppercase English letters A through Z. Always include the count, even when it is 1. Do not combine separated runs of the same letter and do not return global character frequencies. An empty string encodes to an empty string. Leave the input unchanged.
Function
runLengthEncode(s: String) → StringExamples
Example 1
s = "AAAABBCC"return = "A4B2C2"The maximal consecutive runs are AAAA,BB,CC, with lengths 4,2,2. Encoding in order gives A4B2C2, preserving the reported example.
Example 2
s = "ABBA"return = "A1B2A1"The runs are A,BB,A. The separated A runs are not merged, and count 1 is included, giving A1B2A1.
Constraints
- For this exercise, assume 0 <= s.length <= 2000.
- Every character is an uppercase English letter A through Z.