Basic String Compression with Length Guard
Problem statement
Compress a string by replacing every maximal run of equal consecutive characters with the character followed by the run length in base 10.
Return the compressed representation only when it is strictly shorter than the original string. Otherwise, return the original string unchanged. The empty string remains empty.
Function
compressIfShorter(text: String) → StringExamples
Example 1
text = "aabcccccaaa"return = "a2b1c5a3"The run encoding is a2b1c5a3, which is shorter.
Example 2
text = "abcdef"return = "abcdef"The encoded form would be longer, so the original is returned.
Example 3
text = "aa"return = "aa"a2 has the same length as the input, so the input is returned.
Constraints
0 <= text.length <= 100000.textcontains printable ASCII characters.