#C13422. Run-Length Encoding Compression
Run-Length Encoding Compression
Run-Length Encoding Compression
Given a string s
, your task is to compress it using the Run-Length Encoding (RLE) algorithm. In RLE, consecutive occurrences of the same character are replaced by the character followed by the number of occurrences if the count is greater than 1; otherwise, the character is left as is.
For example, if s = "aaabccddd"
, the compressed string should be a3bc2d3
. This problem evaluates your ability to manipulate strings efficiently and handle various edge cases, such as empty strings and strings with mixed characters.
Note: If a character appears only once, it should not be followed by the count.
The mathematical representation of the compression for a string \( s = s_1s_2 \ldots s_n \) can be formalized as follows:
[
RLE(s) = \begin{cases}
"" & \text{if } n = 0,
s_1 & \text{if } n = 1,
s_1 \oplus \Bigl( \sum_{i=2}^{n}\mathbb{I}(s_i \neq s_{i-1}) \Bigr) & \text{otherwise,}
\end{cases}
]
where \(\mathbb{I}(\cdot)\) is the indicator function and \(\oplus\) denotes the concatenation operator.
inputFormat
The input contains a single line with a string s
which may include letters, digits, or symbols.
outputFormat
Output the run-length encoded version of the input string.
## sampleaaabccddd
a3bc2d3