Skip to content

Commit 150f587

Browse files
committed
Add solution #639
1 parent 5054273 commit 150f587

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,7 @@
481481
636|[Exclusive Time of Functions](./0636-exclusive-time-of-functions.js)|Medium|
482482
637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy|
483483
638|[Shopping Offers](./0638-shopping-offers.js)|Medium|
484+
639|[Decode Ways II](./0639-decode-ways-ii.js)|Hard|
484485
643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy|
485486
645|[Set Mismatch](./0645-set-mismatch.js)|Medium|
486487
648|[Replace Words](./0648-replace-words.js)|Medium|

solutions/0639-decode-ways-ii.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 639. Decode Ways II
3+
* https://leetcode.com/problems/decode-ways-ii/
4+
* Difficulty: Hard
5+
*
6+
* A message containing letters from A-Z can be encoded into numbers using the following mapping:
7+
* - 'A' -> "1"
8+
* - 'B' -> "2"
9+
* - 'Z' -> "26"
10+
*
11+
* To decode an encoded message, all the digits must be grouped then mapped back into letters using
12+
* the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped
13+
* into:
14+
* - "AAJF" with the grouping (1 1 10 6)
15+
* - "KJF" with the grouping (11 10 6)
16+
*
17+
* Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is
18+
* different from "06".
19+
*
20+
* In addition to the mapping above, an encoded message may contain the '*' character, which can
21+
* represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*"
22+
* may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or
23+
* "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
24+
*
25+
* Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
26+
*
27+
* Since the answer may be very large, return it modulo 109 + 7.
28+
*/
29+
30+
/**
31+
* @param {string} s
32+
* @return {number}
33+
*/
34+
var numDecodings = function(s) {
35+
const mod = 1e9 + 7;
36+
let [i0, i1, i2, i3] = [1, 0, 0, 0];
37+
38+
for (const c of s) {
39+
if (c == '*') {
40+
i3 = 9 * i0 + 9 * i1 + 6 * i2;
41+
i1 = i0;
42+
i2 = i0;
43+
} else {
44+
i3 = (c > '0') * i0 + i1 + (c <= '6') * i2;
45+
i1 = (c == '1') * i0;
46+
i2 = (c == '2') * i0;
47+
}
48+
i0 = i3 % mod;
49+
}
50+
51+
return i0;
52+
};

0 commit comments

Comments
 (0)