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