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
.
Example 1:
Input: pressedKeys = "22233" Output: 8 Explanation: 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 return 8.
Example 2:
Input: pressedKeys = "222222222222222222222222222222222222" Output: 82876089 Explanation: There are 2082876103 possible text messages Alice could have sent. Since we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.
Constraints:
1 <= pressedKeys.length <= 105
pressedKeys
only consists of digits from'2'
–'9'
.
Solution: DP
Similar to 花花酱 LeetCode 91. Decode Ways, let dp[i] denote # of possible messages of substr s[i:]
dp[i] = dp[i + 1]
+ dp[i + 2] (if s[i:i+1] are the same)
+ dp[i + 3] (if s[i:i+2] are the same)
+ dp[i + 4] (if s[i:i+3] are the same and s[i] in ’79’)
dp[n] = 1
Time complexity: O(n)
Space complexity: O(n) -> O(4)
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Author: Huahua class Solution: def countTexts(self, s: str) -> int: kMod = 10**9 + 7 n = len(s) @cache def dp(i: int) -> int: if i >= n: return 1 ans = dp(i + 1) ans += dp(i + 2) if i + 2 <= n and s[i] == s[i + 1] else 0 ans += dp(i + 3) if i + 3 <= n and s[i] == s[i + 1] == s[i + 2] else 0 ans += dp(i + 4) if i + 4 <= n and s[i] == s[i + 1] == s[i + 2] == s[i + 3] and s[i] in '79' else 0 return ans % kMod return dp(0) |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment