|
| 1 | +# 443. String Compression |
| 2 | + |
| 3 | +## Description |
| 4 | +See https://leetcode.com/problems/string-compression/description/ |
| 5 | + |
| 6 | +## Problem |
| 7 | +Given an array of characters `chars`, compress it using the following algorithm: |
| 8 | + |
| 9 | +Begin with an empty string `s`. For each group of consecutive repeating characters in `chars`: |
| 10 | + |
| 11 | +If the group's length is `1`, append the character to `s`. |
| 12 | +Otherwise, append the character followed by the group's length. |
| 13 | +The compressed string `s` should not be returned separately, but instead, be stored in the input character array `chars`. Note that group lengths that are `10` or longer will be split into multiple characters in chars. |
| 14 | + |
| 15 | +After you are done modifying the input array, return the new length of the array. |
| 16 | + |
| 17 | +You must write an algorithm that uses only constant extra space. |
| 18 | + |
| 19 | +## Example 1 |
| 20 | + |
| 21 | +``` |
| 22 | +Input: chars = ["a","a","b","b","c","c","c"] |
| 23 | +Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] |
| 24 | +Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". |
| 25 | +``` |
| 26 | + |
| 27 | +## Example 2 |
| 28 | + |
| 29 | +``` |
| 30 | +Input: chars = ["a"] |
| 31 | +Output: Return 1, and the first character of the input array should be: ["a"] |
| 32 | +Explanation: The only group is "a", which remains uncompressed since it's a single character. |
| 33 | +``` |
| 34 | + |
| 35 | +## Example 3 |
| 36 | + |
| 37 | +``` |
| 38 | +Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] |
| 39 | +Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. |
| 40 | +Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12". |
| 41 | +``` |
| 42 | + |
| 43 | +## Constraints |
| 44 | + |
| 45 | +``` |
| 46 | +1 <= chars.length <= 2000 |
| 47 | +chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol. |
| 48 | +``` |
0 commit comments