-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompression.java
More file actions
36 lines (31 loc) · 1.06 KB
/
StringCompression.java
File metadata and controls
36 lines (31 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public int getLength(int count) {
if (count == 1) return 1;
else if (count < 10) return 2;
else if (count < 100) return 3;
else return 4;
}
public int getLengthOfOptimalCompression(String s, int k) {
int n = s.length();
int[][] dp = new int[n + 1][k + 1];
for (int i = n; i >= 0; i--) {
for (int j = 0; j <= k; j++) {
if (i == n) {
dp[n][j] = 0;
continue;
}
dp[i][j] = (j > 0) ? dp[i + 1][j - 1] : Integer.MAX_VALUE;
int possible_del = j, count = 0;
for (int end = i; end < n && possible_del >= 0; end++) {
if (s.charAt(end) == s.charAt(i)) {
count++;
dp[i][j] = Math.min(dp[i][j], getLength(count) + dp[end + 1][possible_del]);
} else {
possible_del--;
}
}
}
}
return dp[0][k];
}
}