|
| 1 | +/** |
| 2 | + * 471. Encode String with Shortest Length |
| 3 | + * https://leetcode.com/problems/encode-string-with-shortest-length/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a string s, encode the string such that its encoded length is the shortest. |
| 7 | + * |
| 8 | + * The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets |
| 9 | + * is being repeated exactly k times. k should be a positive integer. |
| 10 | + * |
| 11 | + * If an encoding process does not make the string shorter, then do not encode it. If there are |
| 12 | + * several solutions, return any of them. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {string} s |
| 17 | + * @return {string} |
| 18 | + */ |
| 19 | +var encode = function(s) { |
| 20 | + const n = s.length; |
| 21 | + const dp = Array.from({ length: n }, () => new Array(n).fill('')); |
| 22 | + |
| 23 | + for (let len = 1; len <= n; len++) { |
| 24 | + for (let start = 0; start + len <= n; start++) { |
| 25 | + const end = start + len - 1; |
| 26 | + const substr = s.slice(start, end + 1); |
| 27 | + |
| 28 | + dp[start][end] = substr; |
| 29 | + |
| 30 | + for (let k = 1; k < len; k++) { |
| 31 | + const left = dp[start][start + k - 1]; |
| 32 | + const right = dp[start + k][end]; |
| 33 | + const combined = left + right; |
| 34 | + if (combined.length < dp[start][end].length) { |
| 35 | + dp[start][end] = combined; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + let repeat = 1; |
| 40 | + const patternLen = len; |
| 41 | + while (repeat * patternLen <= n && s.slice(start, start + patternLen).repeat(repeat) |
| 42 | + === s.slice(start, start + repeat * patternLen)) { |
| 43 | + const encoded = `${repeat}[${dp[start][start + patternLen - 1]}]`; |
| 44 | + if (encoded.length < dp[start][end].length) { |
| 45 | + dp[start][end] = encoded; |
| 46 | + } |
| 47 | + repeat++; |
| 48 | + } |
| 49 | + |
| 50 | + for (let k = 1; k < len; k++) { |
| 51 | + if (len % k === 0) { |
| 52 | + const pattern = s.slice(start, start + k); |
| 53 | + if (pattern.repeat(len / k) === substr) { |
| 54 | + const encoded = `${len / k}[${dp[start][start + k - 1]}]`; |
| 55 | + if (encoded.length < dp[start][end].length) { |
| 56 | + dp[start][end] = encoded; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return dp[0][n - 1]; |
| 65 | +}; |
0 commit comments