Class Solution
java.lang.Object
g0401_0500.s0443_string_compression.Solution
443 - String Compression.<p>Medium</p>
<p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p>
<p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p>
<ul>
<li>If the group’s length is <code>1</code>, append the character to <code>s</code>.</li>
<li>Otherwise, append the character followed by the group’s length.</li>
</ul>
<p>The compressed string <code>s</code> <strong>should not be returned separately</strong> , but instead, be stored **in the input character array <code>chars</code> **. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p>
<p>After you are done <strong>modifying the input array</strong> , return <em>the new length of the array</em>.</p>
<p>You must write an algorithm that uses only constant extra space.</p>
<p><strong>Example 1:</strong></p>
<p><strong>Input:</strong> chars = [“a”,“a”,“b”,“b”,“c”,“c”,“c”]</p>
<p><strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [“a”,“2”,“b”,“2”,“c”,“3”]</p>
<p><strong>Explanation:</strong> The groups are “aa”, “bb”, and “ccc”. This compresses to “a2b2c3”.</p>
<p><strong>Example 2:</strong></p>
<p><strong>Input:</strong> chars = [“a”]</p>
<p><strong>Output:</strong> Return 1, and the first character of the input array should be: [“a”]</p>
<p><strong>Explanation:</strong> The only group is “a”, which remains uncompressed since it’s a single character.</p>
<p><strong>Example 3:</strong></p>
<p><strong>Input:</strong> chars = [“a”,“b”,“b”,“b”,“b”,“b”,“b”,“b”,“b”,“b”,“b”,“b”,“b”]</p>
<p><strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: [“a”,“b”,“1”,“2”].</p>
<p><strong>Explanation:</strong> The groups are “a” and “bbbbbbbbbbbb”. This compresses to “ab12”.</p>
<p><strong>Example 4:</strong></p>
<p><strong>Input:</strong> chars = [“a”,“a”,“a”,“b”,“b”,“a”,“a”]</p>
<p><strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [“a”,“3”,“b”,“2”,“a”,“2”].</p>
<p><strong>Explanation:</strong> The groups are “aaa”, “bb”, and “aa”. This compresses to “a3b2a2”. Note that each group is independent even if two groups have the same character.</p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= chars.length <= 2000</code></li>
<li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li>
</ul>
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
compress
public int compress(char[] chars)
-