Given a string of 97 to 6787 characters consisting of lowercase English letters representing signal patterns, write a function to compress it using a custom encoding where sequences of the same letters are replaced by the letter followed by the count of its consecutive occurrences, except when the count is 1, in which case only the letter is written.
Explanation: Step-by-step: with input 'aabcccccaaa', we encounter 'a' for the first time, so we append 'a1'. Then we encounter 'a' again, so we append 'a1'. Next, we encounter 'b' for the first time, so we append 'b1'. Then we encounter 'c' for the first time, so we append 'c1'. After that, we encounter 'c' again, so we append 'c1'. We keep doing this until we reach the end of the string, giving output 'a2b1c5a3'.
Explanation: Step-by-step: with input 'xxyyzz', we encounter 'x' for the first time, so we append 'x1'. Then we encounter 'x' again, so we append 'x1'. Next, we encounter 'y' for the first time, so we append 'y1'. Then we encounter 'y' again, so we append 'y1'. After that, we encounter 'z' for the first time, so we append 'z1'. We keep doing this until we reach the end of the string, giving output 'x2y2z2'.
Master coding challenges related to Strings and solve the [Backup] Galactic Transmission Encoding problem optimally.
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak