639. Decode Ways II
https://leetcode.com/problems/decode-ways-ii/description/
A message containing letters from A-Z is being encoded to numbers using the following mapping way:
'A' -> 1
'B' -> 2
...
'Z' -> 26
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:
Input: "*"
Output: 9
Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".
Example 2:
Input: "1*"
Output: 9 + 9 = 18
Thoughts
给定一个由数字和组成的字符串,数字可以转化成对应的字母(e.g. 1->A, 2->B, ...,26->Z),可看作数字[1, 9],问一共有多少种潜在的转化方法。根据字符串长度分成了N步,每步action为把S[i]或S[i - 1: i]转化成字母,因此DP[i]表前i个字符有多少种转化方式。字符串为空时看作有1种转化方式。*号时由于有多种可能,相当于把前面的解做乘法,并分类讨论所有的可能性。
Code
Analysis
时间复杂度还是O(N), 空间可以O(1), 因为实际只用了i - 1和i - 2.
Last updated
Was this helpful?