[LeetCode] Count Number of Texts

2266. Count Number of Texts

Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.

In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.

  • For example, to add the letter ‘s’, Alice has to press ‘7’ four times. Similarly, to add the letter ‘k’, Alice has to press ‘5’ twice.
  • Note that the digits ‘0’ and ‘1’ do not map to any letters, so Alice does not use them.

However, due to an error in transmission, Bob did not receive Alice’s text message but received a string of pressed keys instead.

  • For example, when Alice sent the message “bob”, Bob received the string “2266622”.

Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.

Since the answer may be very large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int countTexts(string s) {
unordered_map<char, long> mp{{'2',3},{'3',3},{'4',3},{'5',3},{'6',3},{'8',3},{'7',4},{'9',4}};
vector<vector<int>> dp(10, vector<int>(1e5 + 2));

long res = 1, mod = 1e9 + 7, cons = 0, n = s.length();
char prv = '#';
for(int i = 0; i < n; i++) {
auto ch = s[i];
int n = ch & 0b1111;
if(prv != ch) {
if(i) res = (res * dp[prv - '0'][i]) % mod;
prv = ch;
cons = 1;
} else cons++;
for(long j = 1; j <= min(mp[ch], cons); j++) {
dp[n][i + 1] = (dp[n][i + 1] + (dp[n][i - j + 1] ? dp[n][i-j+1] : 1)) % mod;
}
}
res = (res * dp[prv-'0'][n]) % mod;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/08/PS/LeetCode/count-number-of-texts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.