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’.
dp[i][0]为按 1 次 pressedKey[i]作为一个一个字母的数量
dp[i][1]为按 2 次 pressedKey[i]作为一个一个字母的数量
dp[i][2]为按 3 次 pressedKey[i]作为一个一个字母的数量
dp[i][3]为按 4 次 pressedKey[i]作为一个一个字母的数量
dp[i][0]因为跟前面的字母无关,所以应该直接等于 dp[i-1]所有的加和
在 pressedKey[i] == pressedKey[i-1]情况下:
dp[i][1] = dp[i-1][0]
dp[i][2] = dp[i-1][1]
dp[i][3] = dp[i-1][2]
static M: i64 = 1000000007;
impl Solution {
pub fn count_texts(pressed_keys: String) -> i32 {
let chars: Vec<char> = pressed_keys.chars().collect();
let mut dp = vec![vec![0; 4]; pressed_keys.len()];
dp[0][0] = 1;
for i in 1..chars.len() {
if chars[i] == chars[i - 1] {
dp[i][0] = (dp[i - 1][0] + dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][3]) % M;
dp[i][1] = dp[i - 1][0];
dp[i][2] = dp[i - 1][1];
if chars[i] == '7' || chars[i] == '9' {
dp[i][3] = dp[i - 1][2];
}
continue;
}
dp[i][0] = (dp[i - 1][0] + dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][3]) % M;
}
(dp.last().unwrap().into_iter().sum::<i64>() % M) as i32
}
}

本文介绍了一种算法,用于计算从给定的按键序列中可能组成的文本消息数量。通过动态规划方法,考虑了不同按键组合对应的字母及其出现次数,解决了由于传输错误导致的消息失真问题。
186

被折叠的 条评论
为什么被折叠?



