Skip to content

Commit 6f3dc0b

Browse files
committed
Add solution #91
1 parent e4e1b49 commit 6f3dc0b

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy|
9797
89|[Gray Code](./0089-gray-code.js)|Medium|
9898
90|[Subsets II](./0090-subsets-ii.js)|Medium|
99+
91|[Decode Ways](./0091-decode-ways.js)|Medium|
99100
92|[Reverse Linked List II](./0092-reverse-linked-list-ii.js)|Medium|
100101
93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium|
101102
94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy|

solutions/0091-decode-ways.js

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* 91. Decode Ways
3+
* https://leetcode.com/problems/decode-ways/
4+
* Difficulty: Medium
5+
*
6+
* You have intercepted a secret message encoded as a string of numbers. The message
7+
* is decoded via the following mapping:
8+
* "1" -> 'A'
9+
* "2" -> 'B'
10+
* ...
11+
* "25" -> 'Y'
12+
* "26" -> 'Z'
13+
*
14+
* However, while decoding the message, you realize that there are many different
15+
* ways you can decode the message because some codes are contained in other codes
16+
* ("2" and "5" vs "25").
17+
*
18+
* For example, "11106" can be decoded into:
19+
* - "AAJF" with the grouping (1, 1, 10, 6)
20+
* - "KJF" with the grouping (11, 10, 6)
21+
* - The grouping (1, 11, 06) is invalid because "06" is not a valid code (only "6"
22+
* is valid).
23+
*
24+
* Note: there may be strings that are impossible to decode.
25+
*
26+
* Given a string s containing only digits, return the number of ways to decode it.
27+
* If the entire string cannot be decoded in any valid way, return 0.
28+
*
29+
* The test cases are generated so that the answer fits in a 32-bit integer.
30+
*/
31+
32+
/**
33+
* @param {string} s
34+
* @return {number}
35+
*/
36+
var numDecodings = function(s) {
37+
if (s == null || s.length === 0) return 0;
38+
if (s[0] === '0') return 0;
39+
40+
const group = new Array(s.length + 1).fill(0);
41+
group[0] = 1;
42+
group[1] = 1;
43+
44+
for (let i = 2; i <= s.length; i++) {
45+
const a = Number(s.slice(i - 1, i));
46+
if (a >= 1 && a <= 9) {
47+
group[i] += group[i - 1];
48+
}
49+
50+
const b = Number(s.slice(i - 2, i));
51+
if (b >= 10 && b <= 26) {
52+
group[i] += group[i - 2];
53+
}
54+
}
55+
56+
return group[s.length];
57+
};

0 commit comments

Comments
 (0)