Problem
A message containing letters from A-Z can be encoded into numbers using the following mapping:- “AAJF” with the grouping (1 1 10 6)
- “KJF” with the grouping (11 10 6)
Examples
Constraints
- 1 <= s.length <= 10^5
- s[i] is a digit or ’*’.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 639 with 30 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 639 # by problem number
lcpy gen -s decode_ways_ii # by problem name
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
Input: s = "*"
Output: 9
Explanation: The encoded message can represent any of the encoded messages "1" through "9". Each of these can be decoded to the strings "A" through "I" respectively. Hence, there are a total of 9 ways to decode "*".
Input: s = "1*"
Output: 18
Explanation: The encoded message can represent any of the encoded messages "11" through "19". Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K"). Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
Input: s = "2*"
Output: 15
Explanation: The encoded message can represent any of the encoded messages "21" through "29". "21" through "26" have 2 ways of being decoded, but "27" through "29" only have 1 way. Hence, there are a total of (6 * 2) + (3 * 1) = 15 ways to decode "2*".
class Solution:
# Time: O(n)
# Space: O(1)
def num_decodings(self, s: str) -> int:
mod = 1_000_000_007
prev = 1
curr = self._ways_single(s[0])
for i in range(1, len(s)):
pair = self._ways_pair(s[i - 1], s[i])
prev, curr = curr, (curr * self._ways_single(s[i]) + prev * pair) % mod
return curr
def _ways_single(self, ch: str) -> int:
if ch == "*":
return 9
return 0 if ch == "0" else 1
def _ways_pair(self, a: str, b: str) -> int:
if a == "*":
if b == "*":
return 15
return 2 if b <= "6" else 1
if b == "*":
return 9 if a == "1" else (6 if a == "2" else 0)
if a == "0":
return 0
return 1 if int(a + b) <= 26 else 0
| Time | Space |
|---|---|
| O(n) | O(1) |