Skip to content

Commit 8cae1cb

Browse files
committed
add: Decode Ways
1 parent 6994c5e commit 8cae1cb

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
3131
|69|[Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [JavaScript](./src/sqrtx/res.js)|Easy|
3232
|73|[Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [JavaScript](./src/set-matrix-zeroes/res.js)|Medium|
3333
|75|[Sort Colors](https://leetcode.com/problems/sort-colors/) | [JavaScript](./src/sort-colors/res.js)|Medium|
34+
|91|[Decode Ways](https://leetcode.com/problems/decode-ways/) | [JavaScript](./src/decode-ways/res.js)|Medium|
3435
|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | [JavaScript](./src/surrounded-regions/res.js)|Medium|
3536
|136|[Single Number](https://leetcode.com/problems/single-number/) | [JavaScript](./src/single-number/res.js)|Easy|
3637
|175|[Combine Two Tables](https://leetcode.com/problems/combine-two-tables/)| [SQL](./src/combine-two-tables/res.txt)|Easy|

src/decode-ways/res.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* res.js
3+
* @authors Joe Jiang (hijiangtao@gmail.com)
4+
* @date 2017-04-06 18:43:29
5+
*
6+
* A message containing letters from A-Z is being encoded to numbers using the following mapping:
7+
* 'A' -> 1
8+
* 'B' -> 2
9+
* ...
10+
* 'Z' -> 26
11+
*
12+
* Given an encoded message containing digits, determine the total number of ways to decode it.
13+
*
14+
* For example,
15+
* Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
16+
*
17+
* The number of ways decoding "12" is 2.
18+
*
19+
* @param {string} s
20+
* @return {number}
21+
*/
22+
let numDecodings = function(s) {
23+
let len = s.length,
24+
num = 0,
25+
matrix = new Array(len);
26+
27+
if (len===0) return len;
28+
29+
for (let i=0; i<len; i++) {
30+
matrix[i] = new Array(len);
31+
if (s[i] !== '0') {
32+
matrix[i][i] = 1;
33+
} else {
34+
matrix[i][i] = 0;
35+
}
36+
}
37+
38+
let i=0;
39+
for (let j=1; j<len; j++) {
40+
let subOne = 0,
41+
subTwo = 0,
42+
subTwoStr = Number.parseInt(s.substring(j-1, j+1));
43+
44+
if (s[j] !== '0') {
45+
subOne = matrix[i][j-1];
46+
}
47+
if (subTwoStr > 9 && subTwoStr < 27) {
48+
subTwo = j-i === 1? 1:matrix[i][j-2];
49+
}
50+
51+
if (subOne === 0 && subTwo === 0) return 0;
52+
53+
matrix[i][j] = subOne + subTwo;
54+
console.log(matrix[i][j]);
55+
}
56+
57+
return matrix[0][len-1];
58+
};

0 commit comments

Comments
 (0)