Skip to content

Commit 75e488a

Browse files
committed
Leetcode | Count Number of Texts | Java
1 parent 014ea99 commit 75e488a

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

leetcode/src/main/java/com/devstromo/medium/p2266/Solution.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.devstromo.medium.p2266;
22

3+
import java.util.ArrayList;
4+
import java.util.List;
5+
36
public class Solution {
47
private static final int MOD = 1_000_000_007;
58

@@ -21,4 +24,63 @@ public int countTexts(String pressedKeys) {
2124

2225
return dp[n];
2326
}
27+
28+
int mod = (int) 1e9 + 7;
29+
int[] typeMap = new int[]{-1, -1, 0, 0, 0, 0, 0, 1, 0, 1};
30+
31+
public int countTextsBest(String pressedKeys) {
32+
// left * right
33+
List<int[]> list = new ArrayList<>();
34+
int cnt = 0, max = 0;
35+
char prev = '0';
36+
for (char c : pressedKeys.toCharArray()) {
37+
if (prev != c) {
38+
if (prev != '0') list.add(new int[]{(prev - '0'), cnt});
39+
max = Math.max(cnt, max);
40+
cnt = 0;
41+
}
42+
cnt++;
43+
prev = c;
44+
}
45+
if (cnt > 0) {
46+
list.add(new int[]{(prev - '0'), cnt});
47+
max = Math.max(max, cnt);
48+
}
49+
50+
long res = 1;
51+
Long[][] dp = new Long[2][max + 1];
52+
dp[0][0] = 1l;
53+
dp[1][0] = 1l;
54+
for (int i = 0; i < list.size(); i++) {
55+
int[] cur = list.get(i);
56+
int num = cur[0], curCnt = cur[1];
57+
int type = typeMap[num];
58+
59+
long combination = helper(type, curCnt, dp);
60+
61+
res = (res * combination) % mod;
62+
}
63+
64+
return (int) res;
65+
}
66+
67+
// type 0 = 3 char
68+
// type 1 = 4 char
69+
long helper(int type, int cnt, Long[][] dp) {
70+
if (dp[type][cnt] != null) return dp[type][cnt];
71+
72+
for (int i = 1; i <= cnt; i++) {
73+
if (dp[type][i] != null) continue;
74+
75+
if (i == 1) dp[type][i] = 1l;
76+
if (i == 2) dp[type][i] = 2l;
77+
if (i == 3) dp[type][i] = 4l;
78+
// System.out.println(i + " dp[type][i-1]: "+ dp[type][i-1]);
79+
if (i >= 4) {
80+
if (type == 0) dp[type][i] = (dp[type][i - 1] + dp[type][i - 2] + dp[type][i - 3]) % mod;
81+
else dp[type][i] = (dp[type][i - 1] + dp[type][i - 2] + dp[type][i - 3] + dp[type][i - 4]) % mod;
82+
}
83+
}
84+
return dp[type][cnt];
85+
}
2486
}

leetcode/src/test/java/com/devstromo/medium/p2266/SolutionUnitTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ class SolutionUnitTest {
1313
void testCountNumberOfTexts() {
1414
assertEquals(8, solution.countTexts("22233"));
1515
assertEquals(82876089, solution.countTexts("222222222222222222222222222222222222"));
16+
}
1617

18+
@Test
19+
@DisplayName("Test Count Number of Texts Best")
20+
void testCountNumberOfTextsBest() {
21+
assertEquals(8, solution.countTextsBest("22233"));
22+
assertEquals(82876089, solution.countTextsBest("222222222222222222222222222222222222"));
1723
}
1824
}

0 commit comments

Comments
 (0)