#443

String Compression

specialist · 795 · lc medium +31 · verified · 59.6% accepted · 6,151 likes · top 57%

play →

Description

Given a character array chars, compress it in-place using run-length encoding. For each group of consecutive identical characters, write the character to the output; if the group has more than 1 character, also write the count digit-by-digit. Only O(1) extra space may be used.

Return the total length of the compressed data at the front of chars. Characters beyond that position can be ignored.

Example 1:

Input: chars = ["a","a","b","b","c","c","c"]
Output: 6
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".

Example 2:

Input: chars = ["a"]
Output: 1
Explanation: The only group is "a", which remains uncompressed since it's a single character.

Example 3:

Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: 4
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".

Code

1
2
3