Input: pressedKeys ="22233"Output: 8Explanation:
The possible text messages Alice could have sent are:"aaadd","abdd","badd","cdd","aaae","abe","bae", and "ce".Since there are 8 possible messages, we return8.
Input: pressedKeys ="222222222222222222222222222222222222"Output: 82876089Explanation:
There are 2082876103 possible text messages Alice could have sent.Since we need to return the answer modulo 10^9+7, we return2082876103%(10^9+7)=82876089.
We can use dynamic programming to count the number of ways to decode the pressed keys. For each position, we look back up to 3 or 4 previous positions (depending on the digit) to see if a valid group can be formed, and sum the ways to reach those positions.
classSolution {
publicintcountTexts(String pressedKeys) {
int MOD = 1_000_000_007, n = pressedKeys.length();
int[] dp =newint[n+1];
dp[0]= 1;
for (int i = 1; i <= n; i++) {
dp[i]= dp[i-1];
int maxK = (pressedKeys.charAt(i-1) =='7'|| pressedKeys.charAt(i-1) =='9') ? 4 : 3;
for (int k = 2; k <= maxK; k++) {
if (i-k < 0) break;
boolean ok =true;
for (int j = 1; j < k; j++) if (pressedKeys.charAt(i-j-1) != pressedKeys.charAt(i-1)) ok =false;
if (ok) dp[i]= (dp[i]+ dp[i-k]) % MOD;
elsebreak;
}
}
return dp[n];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funcountTexts(pressedKeys: String): Int {
val MOD = 1_000_000_007
val n = pressedKeys.length
val dp = IntArray(n+1)
dp[0] = 1for (i in1..n) {
dp[i] = dp[i-1]
val maxK = if (pressedKeys[i-1] =='7'|| pressedKeys[i-1] =='9') 4else3for (k in2..maxK) {
if (i-k < 0) breakvar ok = truefor (j in1 until k) if (pressedKeys[i-j-1] != pressedKeys[i-1]) ok = falseif (ok) dp[i] = (dp[i] + dp[i-k]) % MOD elsebreak }
}
return dp[n]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defcountTexts(self, pressedKeys: str) -> int:
MOD =10**9+7 n = len(pressedKeys)
dp = [0] * (n+1)
dp[0] =1for i in range(1, n+1):
dp[i] = dp[i-1]
maxk =4if pressedKeys[i-1] in'79'else3for k in range(2, maxk+1):
if i-k <0: breakif all(pressedKeys[i-j-1] == pressedKeys[i-1] for j in range(1, k)):
dp[i] = (dp[i] + dp[i-k]) % MOD
else:
breakreturn dp[n]
impl Solution {
pubfncount_texts(pressed_keys: String) -> i32 {
let m =1_000_000_007;
let n = pressed_keys.len();
let s = pressed_keys.as_bytes();
letmut dp =vec![0; n+1];
dp[0] =1;
for i in1..=n {
dp[i] = dp[i-1];
let maxk =if s[i-1] ==b'7'|| s[i-1] ==b'9' { 4 } else { 3 };
for k in2..=maxk {
if i < k { break; }
if (1..k).all(|j| s[i-j-1] == s[i-1]) {
dp[i] = (dp[i] + dp[i-k]) % m;
} else {
break;
}
}
}
dp[n]
}
}
⏰ Time complexity: O(n), where n is the length of the pressedKeys string. For each position, we check up to 4 previous positions (constant time per position).
🧺 Space complexity: O(n), for the dp array of size n+1.