Class Solution

java.lang.Object
g1501_1600.s1531_string_compression_ii.Solution

public class Solution extends Object
1531 - String Compression II.<p>Hard</p> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_top">Run-length encoding</a> is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;aabccc&quot;</code> we replace <code>&quot;aa&quot;</code> by <code>&quot;a2&quot;</code> and replace <code>&quot;ccc&quot;</code> by <code>&quot;c3&quot;</code>. Thus the compressed string becomes <code>&quot;a2bc3&quot;</code>.</p> <p>Notice that in this problem, we are not adding <code>'1'</code> after single characters.</p> <p>Given a string <code>s</code> and an integer <code>k</code>. You need to delete <strong>at most</strong> <code>k</code> characters from <code>s</code> such that the run-length encoded version of <code>s</code> has minimum length.</p> <p>Find the <em>minimum length of the run-length encoded version of</em> <code>s</code> <em>after deleting at most</em> <code>k</code> <em>characters</em>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> s = &ldquo;aaabcccd&rdquo;, k = 2</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong> Compressing s without deleting anything will give us &ldquo;a3bc3d&rdquo; of length 6. Deleting any of the characters &lsquo;a&rsquo; or &lsquo;c&rsquo; would at most decrease the length of the compressed string to 5, for instance delete 2 &lsquo;a&rsquo; then we will have s = &ldquo;abcccd&rdquo; which compressed is abc3d. Therefore, the optimal way is to delete &lsquo;b&rsquo; and &lsquo;d&rsquo;, then the compressed version of s will be &ldquo;a3c3&rdquo; of length 4.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> s = &ldquo;aabbaa&rdquo;, k = 2</p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong> If we delete both &lsquo;b&rsquo; characters, the resulting compressed string would be &ldquo;a4&rdquo; of length 2.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> s = &ldquo;aaaaaaaaaaa&rdquo;, k = 0</p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong> Since k is zero, we cannot delete anything. The compressed string is &ldquo;a11&rdquo; of length 3.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= s.length <= 100</code></li> <li><code>0 <= k <= s.length</code></li> <li><code>s</code> contains only lowercase English letters.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • getLengthOfOptimalCompression

      public int getLengthOfOptimalCompression(String s, int k)