|
| 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