String Compression
Given an array of characters chars, compress it in place using the following rules:
- Consecutive repeating characters should be replaced with the character followed by its count.
- If a character appears only once consecutively, keep only the character.
- If the count is greater than 9, write each digit of the count separately.
- Return the new length of the compressed array.
Modify the original array in place. Only the first k characters, where k is the returned length, are considered valid.
Example 1
Input
6 a a b b c c
Output
6 a2b2c2
Explanation
Each character appears twice consecutively, so each group is represented by the character followed by 2.
Example 2
Input
7 a a a b b b b
Output
4 a3b4
Explanation
a appears three times and b appears four times. The compressed array becomes a3b4.
Constraints
Hints:
Hint 1
Use one pointer to read each group of identical characters and another pointer to write the compressed result.
Hint 2
When a group contains more than one character, convert its count to a string and write each digit separately.
Author & Technical Reviewer
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output