2266. Count Number of Texts ( Simple DP)

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.

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()];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>