Skip to content

Commit d9ff3ef

Browse files
aQuaaQua
aQua
authored and
aQua
committed
639 wrong answer
1 parent 4d70ab1 commit d9ff3ef

File tree

3 files changed

+413
-0
lines changed

3 files changed

+413
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [639. Decode Ways II](https://leetcode.com/problems/decode-ways-ii/)
2+
3+
## 题目
4+
A message containing letters from `A-Z` is being encoded to numbers using the following mapping way:
5+
6+
```
7+
'A' -> 1
8+
'B' -> 2
9+
...
10+
'Z' -> 26
11+
```
12+
13+
Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers from 1 to 9.
14+
15+
Given the encoded message containing digits and the character '*', return the total number of ways to decode it.
16+
17+
Also, since the answer may be very large, you should return the output mod 109 + 7.
18+
19+
```
20+
Example 1:
21+
Input: "*"
22+
Output: 9
23+
Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".
24+
25+
Example 2:
26+
Input: "1*"
27+
Output: 9 + 9 = 18
28+
```
29+
30+
Note:
31+
1. The length of the input string will fit in range [1, 105].
32+
1. The input string will only contain the character '*' and digits '0' - '9'.
33+
34+
## 解题思路
35+
36+
见程序注释
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package Problem0639
2+
3+
func numDecodings(s string) int {
4+
n := len(s)
5+
if n == 0 {
6+
return 0
7+
}
8+
9+
dp := make([]int, n+1)
10+
// dp[i] 表示 s[:i+1] 的组成方式数
11+
dp[0], dp[1] = 1, one(s[0:1])
12+
13+
for i := 2; i <= n; i++ {
14+
w1, w2 := one(s[i-1:i]), two(s[i-2:i])
15+
dp[i] = dp[i-1]*w1 + dp[i-2]*w2
16+
if dp[i] == 0 {
17+
// 子字符串 s[:i+1] 的组成方式数为 0
18+
// 则,s 的组成方式数肯定也为 0
19+
// 这时可以提前结束
20+
return 0
21+
}
22+
}
23+
24+
return dp[n]
25+
}
26+
27+
// 检查 s 是否为合格的单字符
28+
// len(s) == 1
29+
// 合格, 返回 1
30+
// 不合格, 返回 0
31+
// 注意:
32+
// 题目保证了 s 只含有数字和'*'
33+
func one(s string) int {
34+
switch s[0] {
35+
case '*':
36+
// '*' 可以表示 1~9
37+
return 9
38+
case '0':
39+
return 0
40+
default:
41+
return 1
42+
}
43+
}
44+
45+
// 检查 s 是否为合格的双字符
46+
// len(s) == 2
47+
// 合格, 返回 1
48+
// 不合格, 返回 0
49+
// 注意:
50+
// 题目保证了 s 只含有数字和'*'
51+
func two(s string) int {
52+
switch s[0] {
53+
case '*':
54+
if s[1] == '*' {
55+
return 15
56+
}
57+
if '1' <= s[1] && s[1] <= '6' {
58+
return 2
59+
}
60+
return 1
61+
case '1':
62+
if s[1] == '*' {
63+
return 9
64+
}
65+
return 1
66+
case '2':
67+
if s[1] == '*' {
68+
return 6
69+
}
70+
if s[1] == '7' || s[1] == '8' || s[1] == '9' {
71+
return 0
72+
}
73+
return 1
74+
default:
75+
// '3' <= s[0] && s[0] <= '9',或
76+
// s[0] == '0'
77+
return 0
78+
}
79+
}

0 commit comments

Comments
 (0)