-
Notifications
You must be signed in to change notification settings - Fork 0
/
1531. String Compression II
66 lines (49 loc) · 1.04 KB
/
1531. String Compression II
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution {
public int getLengthOfOptimalCompression(String s, int k)
{
dp = new int[s.length()][k + 1];
Arrays.stream(dp).forEach(A -> Arrays.fill(A, kMax));
return compression(s, 0, k);
}
public static int kMax = 101;
public int[][] dp;
public int compression(String s, int i, int k)
{
if (k < 0)
{
return kMax;
}
if (i == s.length() || s.length() - i <= k)
{
return 0;
}
if (dp[i][k] != kMax)
{
return dp[i][k];
}
int maxFreq = 0;
int[] count = new int[128];
for (int j = i; j < s.length(); ++j)
{
maxFreq = Math.max(maxFreq, ++count[s.charAt(j)]);
dp[i][k] = Math.min( dp[i][k], getLength(maxFreq) + compression(s, j + 1, k - (j - i + 1 - maxFreq)));
}
return dp[i][k];
}
public int getLength(int maxFreq)
{
if (maxFreq == 1)
{
return 1;
}
if (maxFreq < 10)
{
return 2;
}
if (maxFreq < 100)
{
return 3;
}
return 4;
}
}