|
| 1 | +/** |
| 2 | + * 1531. String Compression II |
| 3 | + * https://leetcode.com/problems/string-compression-ii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Run-length encoding is a string compression method that works by replacing consecutive |
| 7 | + * identical characters (repeated 2 or more times) with the concatenation of the character |
| 8 | + * and the number marking the count of the characters (length of the run). For example, |
| 9 | + * to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus |
| 10 | + * the compressed string becomes "a2bc3". |
| 11 | + * |
| 12 | + * Notice that in this problem, we are not adding '1' after single characters. |
| 13 | + * |
| 14 | + * Given a string s and an integer k. You need to delete at most k characters from s such that |
| 15 | + * the run-length encoded version of s has minimum length. |
| 16 | + * |
| 17 | + * Find the minimum length of the run-length encoded version of s after deleting at most |
| 18 | + * k characters. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {string} s |
| 23 | + * @param {number} k |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var getLengthOfOptimalCompression = function(s, k) { |
| 27 | + const n = s.length; |
| 28 | + const dp = new Array(n + 1).fill().map(() => new Array(k + 1).fill(9999)); |
| 29 | + dp[0][0] = 0; |
| 30 | + |
| 31 | + for (let i = 1; i <= n; i++) { |
| 32 | + for (let j = 0; j <= k; j++) { |
| 33 | + let count = 0; |
| 34 | + let deletions = 0; |
| 35 | + |
| 36 | + for (let m = i; m >= 1; m--) { |
| 37 | + if (s[m - 1] === s[i - 1]) count++; |
| 38 | + else deletions++; |
| 39 | + |
| 40 | + if (j - deletions >= 0) { |
| 41 | + dp[i][j] = Math.min( |
| 42 | + dp[i][j], |
| 43 | + dp[m - 1][j - deletions] + calculateEncodedLength(count) |
| 44 | + ); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if (j > 0) { |
| 49 | + dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return dp[n][k]; |
| 55 | + |
| 56 | + function calculateEncodedLength(count) { |
| 57 | + if (count === 0) return 0; |
| 58 | + if (count === 1) return 1; |
| 59 | + if (count < 10) return 2; |
| 60 | + if (count < 100) return 3; |
| 61 | + return 4; |
| 62 | + } |
| 63 | +}; |
0 commit comments