Press "Enter" to skip to content

Posts tagged as “decode”

花花酱 LeetCode 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.

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

花花酱 LeetCode 639. Decode Ways II

Problem:

A message containing letters from A-Z is being encoded to numbers using the following mapping way:

Beyond that, now the encoded string can also contain the character ‘*’, which can be treated as one of the numbers from 1 to 9.

Given the encoded message containing digits and the character ‘*’, return the total number of ways to decode it.

Also, since the answer may be very large, you should return the output mod 109 + 7.

Example 1:

Example 2:

Note:

  1. The length of the input string will fit in range [1, 105].
  2. The input string will only contain the character ‘*’ and digits ‘0’ – ‘9’.

Idea:

DP

Time complexity: O(n)

Space complexity: O(1)

Solution:

C++

 

Related Problems: