In order to add a letter, Alice has to press the key of the corresponding digit
i
times, wherei
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
.Note: except for 7 and 9, the number can be decoded as 3 letters. 7 and 9 can be decoded as 4 letters
It is quite a simple question because only repeating numbers can be decoded as different letters. For example, 111 can be decoded as [aaa, ab, ba, c]. However for 14, '14' can not be decoded as a single letter, that's why I said this is not a complicated problem.
As we know only repeating numbers can be decoded as different letters, we can check whether the previous number is the same or not, if it is the same we can keep checking the previous number by the possible decoded ways of the numbers.
We would accumulate the decode ways to get the total decode ways.
class Solution {
public:
int countTexts(string pressedKeys) {
int dp[pressedKeys.length() + 1];
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for(int i = 1; i <= pressedKeys.length() ; i++){
dp[i] = dp[i-1];
if(i - 2 >= 0 && pressedKeys[i-2] == pressedKeys[i-1]){
dp[i] = (dp[i] + dp[i-2]) % int(1e9 + 7);
if(i - 3 >= 0 && pressedKeys[i-3] == pressedKeys[i-2]){
dp[i] = (dp[i] + dp[i-3]) % int(1e9 + 7);
if(i - 4 >= 0 && pressedKeys[i-4] == pressedKeys[i-3])
if (pressedKeys[i-1] == '7'|| pressedKeys[i-1] == '9')){
dp[i] = (dp[i] + dp[i-4]) % int(1e9 + 7);
}
}
}
}
return dp[pressedKeys.length()];
}
};