forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathString Compression II.js
More file actions
23 lines (20 loc) · 845 Bytes
/
String Compression II.js
File metadata and controls
23 lines (20 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var getLengthOfOptimalCompression = function(s, k) {
const memo = new Map()
const backtrack = (i, lastChar, lastCharCount, k) => {
if (k < 0) return Number.POSITIVE_INFINITY
if (i >= s.length) return 0
const memoKey = `${i}#${lastChar}#${lastCharCount}#${k}`
if (memoKey in memo) return memo[memoKey]
if (s[i] === lastChar) {
const incrementor = [1, 9, 99].includes(lastCharCount) ? 1 : 0
memo[memoKey] = incrementor + backtrack(i+1, lastChar, lastCharCount+1, k)
} else {
memo[memoKey] = Math.min(
1 + backtrack(i+1, s[i], 1, k), //keep char
backtrack(i+1, lastChar, lastCharCount, k-1) //delete char
)
}
return memo[memoKey]
}
return backtrack(0, '', 0, k)
};